Combining For Loop outputs into a Matrix

조회 수: 5 (최근 30일)
nico nico
nico nico 2017년 11월 27일
댓글: nico nico 2017년 11월 28일
Hi, I'm relatively new to Matlab. This is my code:
b = 0:3;
for q = 0:10:20
XY = (40 + 2*q) + cosd(b)
end
And the output on the command window would be:
XY =
41.0000 40.9998 40.9994 40.9986
XY =
61.0000 60.9998 60.9994 60.9986
XY =
81.0000 80.9998 80.9994 80.9986
I'm struggling to combine the outputs into one matrix like this:
XY =
41.0000 40.9998 40.9994 40.9986
61.0000 60.9998 60.9994 60.9986
81.0000 80.9998 80.9994 80.9986
Suggestions/hints would be much appreciated, thanks!

채택된 답변

dpb
dpb 2017년 11월 27일
With a loop, you just index...
b = 0:3;
XY=zeros(3,length(b)); % preallocate the output array
irow=0; % row counter
for q = 0:10:20
irow=irow+1; % increment counter
XY(irow,:) = (40 + 2*q) + cosd(b);
end
BUT, you "don't need no steenkin' loops!" with Matlab; that's the power of the language with the vectorized functions--
> [Q,B]=meshgrid(q,b); % generate the grid of points in bot variables
>> XY = [(40 + 2*Q) + cosd(B)].'
XY =
41.0000 40.9998 40.9994 40.9986
61.0000 60.9998 60.9994 60.9986
81.0000 80.9998 80.9994 80.9986
>>

추가 답변 (1개)

Stephen23
Stephen23 2017년 11월 27일
편집: Stephen23 2017년 11월 27일
>> b = 0:3;
>> q = 0:10:20;
>> XY = bsxfun(@plus,40+2*q(:),cosd(b))
XY =
41 40.9998476951564 40.9993908270191 40.9986295347546
61 60.9998476951564 60.9993908270191 60.9986295347546
81 80.9998476951564 80.9993908270191 80.9986295347546

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by