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 CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by