Save loop data to a matrix

조회 수: 2 (최근 30일)
Harshil Patel
Harshil Patel 2016년 3월 2일
댓글: Muhamad Bunaiya 2018년 4월 5일
Hello,
It would be a great help if someone could suggest a way to save data from the loop in a matrix. I am using the following code.
p = [1,2,3;4,5,6];
for i = 1:3
x = p(1,i);
y = p(2,i);
u1 = [x*y x/y 2*x];
u2 = [y/x x*y y/2];
end
For each iteration of the loop, the values of u1 and u2 will change. Now, I want to store this u1 and u2 values in matrix U, such that at the end of the loop U will be:
U =
u1 %from i = 1
u2 %from i = 1
u1 %from i = 2
u2 %from i = 2
u1 %from i = 3
u2 %from i = 3
I have searched through numerous threads on similar topics but haven't found a satisfactory answer. Could someone please help me with this.
Thanking You,
Harshil
  댓글 수: 1
Muhamad Bunaiya
Muhamad Bunaiya 2018년 4월 5일
xt=[1 2 3 4 5 6 7 8 9 10 11] for m=1:25
Output supposely xt1 = [1 2 3 4 5 6 7 8 9 10 11] xt2 =[1 2 3 4 5 6 7 8 9 10 11] . . . . . . . xt25 =[1 2 3 4 5 6 7 8 9 10 11] What should i do to get this output

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

채택된 답변

Guillaume
Guillaume 2016년 3월 2일
To do exactly what you asked:
p = [1,2,3;4,5,6];
U = zeros(size(p, 2)*2, 3);
for i = 1:size(p, 2) %don't use hardcoded constants when you can just query the size
x = p(1,i);
y = p(2,i);
U(2*i-1, :) = [x*y x/y 2*x];
U(2*i, :) = [y/x x*y y/2];
end
However, I don't think interleaving your u1 and u2 is a good idea. It makes it more difficult to index. Instead, I would put u1 and u2 in the same row:
p = [1,2,3;4,5,6];
U = zeros(size(p, 2), 6);
for i = 1:size(p, 2) %don't use hardcoded constants when you can just query the size
x = p(1,i);
y = p(2,i);
U(i, 1:3) = [x*y x/y 2*x];
U(i, 4:6) = [y/x x*y y/2];
end
  댓글 수: 1
Harshil Patel
Harshil Patel 2016년 3월 2일
Thanks a lot mate!

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

추가 답변 (0개)

카테고리

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