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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by