storing values of for loop in a matrix

조회 수: 11 (최근 30일)
Sumera Yamin
Sumera Yamin 2021년 2월 2일
댓글: Sumera Yamin 2021년 2월 2일
Hi, i have a basic problem. i am using nested for loops x and y and calculating variable z. the variable z is over written at each iteration. at the end of loops, i want to have the variable z matrix. The x is 1xm vector, and y=1xn vector, how would i get the data matrix for z, where z=mxn. i use a simple test code below. Many thanks for any help
x=-60:0.5:-50;
y=-10:0.5:-5;
z=[];
for i=1:length(x)
for j=1:length(y)
z=x(i)+y(j)
end
end

채택된 답변

Stephen23
Stephen23 2021년 2월 2일
편집: Stephen23 2021년 2월 2일
x = -60:0.5:-50;
y = -10:0.5:-5;
z = nan(numel(x),numel(y)); % better to preallocate array.
for i = 1:numel(x)
for j = 1:numel(y)
z(i,j) = x(i)+y(j); % indexing to allocate value to z.
end
end
  댓글 수: 1
Sumera Yamin
Sumera Yamin 2021년 2월 2일
hi, many thanks for your quick response. this works perfectly.

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

추가 답변 (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