Effacer les filtres
Effacer les filtres

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

6 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Image Analyst
Image Analyst le 25 Déc 2019
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.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices 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