I worked on nested loop.

2 Ansichten (letzte 30 Tage)
seema niran
seema niran am 7 Okt. 2015
Kommentiert: seema niran am 7 Okt. 2015
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.

Akzeptierte Antwort

per isakson
per isakson am 7 Okt. 2015
Bearbeitet: per isakson am 7 Okt. 2015
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 Kommentar
seema niran
seema niran am 7 Okt. 2015
yes sir , i got the correct matrix when i incremented j (j=j+23) in the first loop. thank you for the comment

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Stalin Samuel
Stalin Samuel am 7 Okt. 2015
A_new = ones(46,24)
A = rand(5000,24);
A_new(1:23,:) = A(1,:);
A_new(24:46,:) = A(2,:) ;

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by