一,普通數組:
1,下標遍歷:
v=[1,4,6,4,1]; |
結果:16
2,元素遍歷:
v=[1,4,6,4,1]; s=0; for ve=v s=s+ve; end disp(s); |
結果: 16
二,元胞數組:
1,下標遍歷
strvec={'i','am','iwantnon'}; str=[]; for i=1:length(strvec) str=[str,' ',strvec{i}]; end disp(str); |
結果:i am iwantnon
2,元素遍歷:
strvec={'i','am','iwantnon'}; str=[]; for s=strvec str=[str,' ',s{1}]; end disp(str); |
結果:i am iwantnon
注:二,2中的s是1*1 cell,要訪問之需用s{1}。
--
元素遍歷的一個應用:
如果被遍歷數組的元素本身是下標(例如find函數的返回值index數組),那麼用元素遍歷更自然:
index=find(A==0); for i=index A(i)=...; end |