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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by