Can anyone show me how I can avoid following for loops

*Hello everyone,
Can anyone show me how I can avoid following for loops.
Thanks!*
mth=0;
nth=0;
for i=1:1000
ML = [1,2;3,4];
for ix=1:size(ML,1)
for iy=1:size(ML,2)
M(mth+ix,nth+iy)=ML(ix,iy);
end
end
mth = mth+size(ML,1);
nth = nth+size(ML,2);
end

 採用された回答

Matt Fig
Matt Fig 2012 年 10 月 8 日
編集済み: Matt Fig 2012 年 10 月 8 日

0 投票

Here is a one approach:
M = diag(repmat([1 4],1,1000)) +...
diag([repmat([2 0],1,999) 2],1) +...
diag([repmat([3 0],1,999) 3],-1);
And another:
M = diag(repmat([1 4],1,1000));
M(2001:2001:end) = [repmat([2 0],1,999) 2];
M(2:2001:end) = [repmat([3 0],1,999) 3];

1 件のコメント

hung lequang
hung lequang 2012 年 10 月 8 日
Very nice approach. Thanks again.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2012 年 10 月 8 日

0 投票

for iy=1:size(ML,2)
M(mth+ix,nth+iy)=ML(ix,iy);
end
can be written as
MLc = size(ML,2);
M(mth+ix, nth:nth+MLc-1) = ML(ix, 1:MLc);

3 件のコメント

Daniel Shub
Daniel Shub 2012 年 10 月 8 日
編集済み: Daniel Shub 2012 年 10 月 8 日
Are you sure? If nth is 0 and MLc is 2, nth:nth+MLc-1 gives [0, 1] which causes indexing problems. I think it is nth+(1:MLc) on the RHS.
Walter Roberson
Walter Roberson 2012 年 10 月 8 日
編集済み: Walter Roberson 2012 年 10 月 8 日
Yes, that would make sense on the LHS.
Daniel Shub
Daniel Shub 2012 年 10 月 8 日
Yes, LHS not RHS...

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by