complicated for loop with 2 requirements or constraints

조회 수: 4 (최근 30일)
Grace
Grace 2014년 6월 4일
댓글: Grace 2014년 6월 4일
Hi,I have
a=[1 2; 3 4; 5 6;7 8];
Suppose I want my result to have two sets of number, which set 1 is [1 2; 3 4; 5 6] and set 2=[3 4; 5 6;7 8].
result=cell(2,1);
for m=1:2
for i=0:1
k=1:3;
result{m}=a(k+i,:);
end
end
This output shows 2 similar set of numbers. What can I do? Do I make myself clear?

채택된 답변

Roger Wohlwend
Roger Wohlwend 2014년 6월 4일
Then do the following:
if m > 4
UT{m} = id(m-4:m-1,:)
end
  댓글 수: 1
Grace
Grace 2014년 6월 4일
Hi Roger, now I'm trying to modify my original id by sorting its column to get 2 new id as follows:
id = [ 1 3; 2 6; 3 2; 4 5; 5 1; 6 4; 7 7];
[r c]=size(id);
new_id=cell(c,1);
UT=cell(r*c,1);
for col=1:c
new_id{col}=sortrows(id,col);
for m=1:7
if m>4
UT{m} = new_id(m-4:m-1,:);
else
j=1:m-1;
a=new_id(j,:);
i=m:4;
b=new_id(i+3,:);
UT{m}=cat(1,a,b);
end
end
end
Then from that two new id, i want to run the if else statement to get UT, but now I have 2 new id, means that I will get 14 UTs. But if i run the code above, there is an error, I can't get what I wanted.
Can you help? Thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Roger Wohlwend
Roger Wohlwend 2014년 6월 4일
In the second loop you first (when i = 0) save a matrix in result{m} and then you override it when (i = 1). So the inner loop has no effect.
I do not understand why you use loops at all. You could simply write:
result{1} = a(1:3,:);
result{2} = a(2:4,:);
Or if you want a loop:
for m = 1 : 2
result{m} = a(m:m+2,:);
end

카테고리

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