Azzera filtri
Azzera filtri

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

6 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Image Analyst
Image Analyst il 25 Dic 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.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by