필터 지우기
필터 지우기

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