I worked on nested loop.

2 ビュー (過去 30 日間)
seema niran
seema niran 2015 年 10 月 7 日
コメント済み: seema niran 2015 年 10 月 7 日
y is a 5000 by 24 matrix. i need a new 46 by 24 matrix such that row 1 of y repeats 23 times and row 2 repeats 23 times. the code is given below
p=1;
k=1;
a=ones([1,24]);
while k<3
sub=y(k,:);
k=k+1;
while j<24
a(j,:)=sub;
j=j+1;
end
end
the answer i expect is a 46 by 24 matrix. but i get a 23 by 24 matrix.

採用された回答

per isakson
per isakson 2015 年 10 月 7 日
編集済み: per isakson 2015 年 10 月 7 日
Assuming that your goal is to understand loops, try this
>> [ a01, a02 ] = cssm();
>> all(a01(:)==a02(:))
ans =
1
where
function [ a01, a02 ] = cssm()
y = randi( 100, [3,24] );
a01 = nan([46,24]);
a02 = nan([46,24]);
kk = 1;
while kk<3
sub = y(kk,:);
kk = kk+1;
jj = 1;
while jj<24
a01((kk-2)*23+jj,:)=sub;
jj = jj+1;
end
end
for kk = 1 : 2
for jj = 1 : 23
a02((kk-1)*23+jj,:) = y(kk,:);
end
end
end
&nbsp
Comment: &nbsp The codes based on while-loops and for-loops, respectively, produces identical answers. In this special case for-loops are easier to work with than while-loops.
"but i get a 23 by 24 matrix". That's because in the second turn of the outer loop the counter, j, has the value 24 and the code of the inner loop will not execute.
Stalin's answer provides a more efficient solution, which takes advantage of special features of Matlab.
  1 件のコメント
seema niran
seema niran 2015 年 10 月 7 日
yes sir , i got the correct matrix when i incremented j (j=j+23) in the first loop. thank you for the comment

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

その他の回答 (1 件)

Stalin Samuel
Stalin Samuel 2015 年 10 月 7 日
A_new = ones(46,24)
A = rand(5000,24);
A_new(1:23,:) = A(1,:);
A_new(24:46,:) = A(2,:) ;

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by