필터 지우기
필터 지우기

Result producing 1x5 array instead of 10x5?

조회 수: 4 (최근 30일)
Thomas Veith
Thomas Veith 2019년 6월 4일
댓글: Alex Mcaulley 2019년 6월 4일
Hi all,
I have the following code which I'm expecting to produce a 10x5 array but it's only giving me a 1x5, and I'm not sure why?
n = 10;
result = zeros(n,5);
for k=1:n;
A0=1;P0=29;g=rand;p=rand;B=rand;
result = [A0,P0,g,p,B];
end;
Alternatively, if I write the code this way I get a 10x1 cellular array, each entry of which represents a 1x5 numeric array. This gives me the number of results I want, but not in the format I'm looking for (which, again, is ultimately a 10x5 array). Thanks in advance!
n = 10;
result = cell(n,1);
for k=1:n;
A0=1;P0=29;g=rand;p=rand;B=rand;
result{k} = {A0,P0,g,p,B};
end;

채택된 답변

Alex Mcaulley
Alex Mcaulley 2019년 6월 4일
You need to specify the index:
n = 10;
result = zeros(n,5);
for k=1:n;
A0=1;P0=29;g=rand;p=rand;B=rand;
result(k,:) = [A0,P0,g,p,B];
end;
  댓글 수: 4
madhan ravi
madhan ravi 2019년 6월 4일

That would just copy the same g p B values through repmat() so creating n elements for g p B and then copying it into the matrix would be better.

Alex Mcaulley
Alex Mcaulley 2019년 6월 4일
Yes, as @madhan said, if you want random numbers for all rows:
n = 10;
A0=1;P0=29;
result = [repmat([A0,P0],n,1),rand(n,3)]

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

추가 답변 (1개)

Rob L
Rob L 2019년 6월 4일
Your first method overwites the result every loop with a [ 1 x 5 ] array.
You could (among many other solutions) use:
n = 10;
result = zeros(n,5);
for k=1:n
A0=1;P0=29;g=rand;p=rand;B=rand;
result(k,1) = A0;
result(k,2) = P0;
result(k,3) = g;
result(k,4) = p;
result(k,5) = B;
end

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by