storing values of for loop in a matrix

10 visualizaciones (últimos 30 días)
Sumera Yamin
Sumera Yamin el 2 de Feb. de 2021
Comentada: Sumera Yamin el 2 de Feb. de 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

Respuesta aceptada

Stephen23
Stephen23 el 2 de Feb. de 2021
Editada: Stephen23 el 2 de Feb. de 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 comentario
Sumera Yamin
Sumera Yamin el 2 de Feb. de 2021
hi, many thanks for your quick response. this works perfectly.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by