Problem for creating matrix with loop

조회 수: 4 (최근 30일)
sermet
sermet 2014년 1월 15일
댓글: Kelly Kearney 2014년 1월 16일
A=[1 2 3;4 5 6;7 8 9]
%I wanna create a loop like that
for i=2:3
A(1:i,:)
end
%What I'm trying to do is getting these matrixes from the loop,
A_1= A(2:2,:)
A_2= A(3:2,:)
For retrieve these matrixes from the loop, what equation I should write in the loop?

채택된 답변

Kelly Kearney
Kelly Kearney 2014년 1월 15일
Your loop and your example aren't the same, since A(3:2,:) is an empty matrix. But I assume you want this:
for ii = 1:10
B{ii} = A(1:ii,:);
end
This won't work with your example A, which only has 3 rows, but I'm assuming your real A must have 10.
But really, as others have mentioned, it seems a little pointless to create these arrays, since using A(1:ii,:) only adds a few keystrokes over B{ii}, and doesn't involve the unnecessary replication of data.
  댓글 수: 3
sermet
sermet 2014년 1월 15일
lastly I'm explaining my situation;
A=[1 2;3 4;5 6] for example
for i=2:3
A(1:i,:)
end
results;
ans = 1 2 3 4
ans = 1 2 3 4 5 6
How can I spare each of them? I mean when I type ans(2) or ans(1) it should give me the result.
Kelly Kearney
Kelly Kearney 2014년 1월 16일
ans is a temporary variable that gets used any time that you fail to explicitly assign function output to a variable. I showed you how to assign that data to a variable; if you type B{1} or B{2}, you'll see your results.
Although A(1:2,:) does not equal [1 2 3 4]; it is [1 2; 3 4]. If you want the former, it would be
for ii = 2:3
B{ii-1} = reshape(A(1:ii,:)', 1, []);
end

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

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2014년 1월 15일
편집: Azzi Abdelmalek 2014년 1월 15일
What is the purpose of creating other variables, when you can access any part of your matrix, whenever you want.
If you want A(2:2,:) , you don't need to create a variable A_1, just write
A(2:2,:)
Or you can create a cell array B
B{1}=A(2:2,:)
B{2}=A(3:2,:)
  댓글 수: 3
sermet
sermet 2014년 1월 15일
편집: Azzi Abdelmalek 2014년 1월 15일
then retrieve it from the loop. For example,
for i=2:10
A(1:i,:)
end
A2,A3,....A10 must be created from this loop. What I need is how to retrieve these matrixes from this loop.
Azzi Abdelmalek
Azzi Abdelmalek 2014년 1월 15일
편집: Azzi Abdelmalek 2014년 1월 15일
k=1;
for i=2:10
k=k+1;
B{k}=A(1:i,:)
end
B{2}
B{3}

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

카테고리

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