Filter löschen
Filter löschen

how to write a function that multiplies any 2 matrices that are of compatible size by using nested for loop?

1 Ansicht (letzte 30 Tage)
For example not just a (2X2)matrix, but also for a (3X1) matrix and (3X3) matrix. I'm confused by a nested loop ? How do you nest it anyway? Thanks I am new to matlab

Antworten (1)

Bjorn Gustavsson
Bjorn Gustavsson am 27 Nov. 2015
You simply do something along these lines:
for i1 = 1:size(M1,1)
for i2 = 1:size(M2,2),
Res(i1,i2) = M1(i1,i2) + M2(i1,i2); % Or whatever operator you're interested in
end
end
Above I've not bothered checking that this is the proper ordering of the indexing for your desired multiplication of matrices - since the * operator in matlab is intended to do matrix multiplication for you, I guess this is for the learning experience...
You should also pre-allocate the Res array (Res = zeros(sy,sx);) to avoid growing it incrementally which wastes lot of time.
HTH

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by