Understanding Index for loop
1 次查看(过去 30 天)
显示 更早的评论
I am new to Matlab, and I would like to understand the following index in for loop ...
I understand the indices of the values are different but they are equal in number ??
Can anyone explain to me more ??
clear all;
clc;
y=[0 .4 .8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0];
z=zeros(1,length(y));
x=[0 0.8 1.6 2.4 3.2 4.0 4.8 5.6 6.4 7.2 8];
for i=1:length(x)
for j=1:11
b(:,:,i)=x(1,i) + z(1,i); % Why both b are NOt the same... I understand the indicies are different but both are 11 ??
b_j(:,:,i)=x(1,j) + z(1,j);
end
end
0 个评论
回答(1 个)
KSSV
2020-6-8
Becuase the values you are saving are different......in the value b_j
If you see you have used idex i.; so only the last value of i i.e length(x) will be saved.....every time it will save the last value of b. If you replace that index with i, then both will be same.
y=[0 .4 .8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0];
z=zeros(1,length(y));
x=[0 0.8 1.6 2.4 3.2 4.0 4.8 5.6 6.4 7.2 8];
for i=1:length(x)
for j=1:11
b(:,:,i)=x(1,i) + z(1,i); % Why both b are NOt the same... I understand the indicies are different but both are 11 ??
b_j(:,:,j)=x(1,j) + z(1,j);
end
end
isequal(b,b_j)
Any ways, you are calculating b_j repeatedly ..I don't know what you are trying to understand, but I think you got it what I meant to say.
NOTE: Read about initilaization. Read about indexing.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!