フィルターのクリア

How to add two vectors using for loop? i have to do addition of A and B using for loop.

6 ビュー (過去 30 日間)
A = [7 21 30 40];
B = [11 4 14 6];
for i = 1:size(A,1)
for j = 1:size(B,1)
D = A + B
end
end

採用された回答

Image Analyst
Image Analyst 2019 年 12 月 25 日
size() for a 2-D matrix gives [rows, columns]. As you can see, you have 1 row and 4 columns. Inside the loop, you need to give everything indexes. So you'd do
A = [7 21 30 40];
B = [11 4 14 6];
[rows, columns] = size(A); % Assume B matches the number of rows and columns.
for i = 1:columns
for j = 1:rows
D(j, i) = A(j, i) + B(j, i)
end
end
The above code will work for 1-D row vectors (like you have) and also for 2-D matrices.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by