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

1 次查看(过去 30 天)
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

回答(1 个)

Bjorn Gustavsson
Bjorn Gustavsson 2015-11-27
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by