I worked on nested loop.

2 次查看(过去 30 天)
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