I worked on nested loop.

2 vues (au cours des 30 derniers jours)
seema niran
seema niran le 7 Oct 2015
Commenté : seema niran le 7 Oct 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.

Réponse acceptée

per isakson
per isakson le 7 Oct 2015
Modifié(e) : per isakson le 7 Oct 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 commentaire
seema niran
seema niran le 7 Oct 2015
yes sir , i got the correct matrix when i incremented j (j=j+23) in the first loop. thank you for the comment

Connectez-vous pour commenter.

Plus de réponses (1)

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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by