storing values of for loop in a matrix

11 Ansichten (letzte 30 Tage)
Sumera Yamin
Sumera Yamin am 2 Feb. 2021
Kommentiert: Sumera Yamin am 2 Feb. 2021
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

Akzeptierte Antwort

Stephen23
Stephen23 am 2 Feb. 2021
Bearbeitet: Stephen23 am 2 Feb. 2021
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 Kommentar
Sumera Yamin
Sumera Yamin am 2 Feb. 2021
hi, many thanks for your quick response. this works perfectly.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by