storing values of for loop in a matrix

12 vues (au cours des 30 derniers jours)
Sumera Yamin
Sumera Yamin le 2 Fév 2021
Commenté : Sumera Yamin le 2 Fév 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

Réponse acceptée

Stephen23
Stephen23 le 2 Fév 2021
Modifié(e) : Stephen23 le 2 Fév 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 commentaire
Sumera Yamin
Sumera Yamin le 2 Fév 2021
hi, many thanks for your quick response. this works perfectly.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by