不同的迭代输出
我在 matlab 中有这个
A=34;
for i =1:1:6
A = A + 1;
t1=fix(A/(2*32));
t2=fix((A-(t1*64))/(32));
t3=fix(((A-(t1*64)) - (t2*32))/(16));
G = [t1 t2 t3]
end
,当它显示时,它给出
G= 0 1 0
G= 0 1 0
G= 0 1 0 ....to the 6th G(the values are not right anyway)
but I want to have an output of
G1= 0 1 0
G2= 0 1 0
G3= 0 1 0....to G6
然后 cat.or 将它们放入一组 G = [G1, G2, G3, ...,G6] 中。请问我该如何完成此操作?
I have this in matlab
A=34;
for i =1:1:6
A = A + 1;
t1=fix(A/(2*32));
t2=fix((A-(t1*64))/(32));
t3=fix(((A-(t1*64)) - (t2*32))/(16));
G = [t1 t2 t3]
end
When it displays, it gives
G= 0 1 0
G= 0 1 0
G= 0 1 0 ....to the 6th G(the values are not right anyway)
but I want to have an output of
G1= 0 1 0
G2= 0 1 0
G3= 0 1 0....to G6
and then cat.or put them into a set of G = [G1, G2, G3, ...,G6].Please how do I get this done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于您的问题,有几点需要解决...
预分配数组和矩阵索引:
如果您想保存每次迭代生成的值,您可以 在循环之前将数组预分配为 6×3 零矩阵,然后 在循环中索引到矩阵的给定行以存储值:
矢量化运算:
在许多情况下,您可以在 MATLAB 中完全避免 for 循环,并且通常可以通过使用 矢量化操作。在您的情况下,您可以为
A
创建一个值向量,并对t1
、t2
和t3
执行计算code> 使用 算术数组运算符 < code>.* 和./
:这里的好处是
G
将自动以包含您想要的所有值的 6×3 矩阵结束,因此不需要预分配或索引。显示输出:
如果要创建与在行尾省略分号时出现的默认数字显示不同的格式化输出,可以使用诸如
fprintf
。例如,要获得您想要的输出,您可以在创建G
后运行它,如下所示:There are a few points to address regarding your question...
Preallocating arrays and matrix indexing:
If you want to save the values you generate on each iteration, you can preallocate the array
G
as a 6-by-3 matrix of zeroes before your loop and then index into a given row of the matrix within your loop to store the values:Vectorized operations:
In many cases you can avoid for loops altogether in MATLAB and often get a speed-up in your code by using vectorized operations. In your case, you can create a vector of values for
A
and perform your calculations fort1
,t2
, andt3
on an element-wise basis using the arithmetic array operators.*
and./
:The bonus here is that
G
will automatically end up as a 6-by-3 matrix containing all the values you want, so no preallocation or indexing is necessary.Displaying output:
If you want to create formatted output that differs from the default display of numbers that occurs when you leave off the semicolon at the end of a line, you can use functions like
fprintf
. For example, to get the output you want you could run this after creatingG
as above:如果我理解正确的话,你的问题只是输出(以便所有值都存储在 G 中),对吧?
你可以尝试这个:
这应该用新计算的值扩展 G
If I understood you correctly your problem is just the output (so that all values are stored in G), right?
You might try this:
This should expand G with the newly computed values