Given two real square matrix of order n. Get a new matrix of the elements of each column of the first matrix times elements of the corresponding rows of the second matrix. i coded using matlab but unfortunately it applys only for (3x3)matrix.what should i do so that it may apply for every kind of matrix, for example(4x4),(5x5) and more.
codes
clc
clear
a=[1 2 3;4 5 6;7 8 9];
b=[1 2 3;4 5 6;7 8 9];
for i=1:length(a)
for j=1:length(b)
c(i,j)=a(i,j)*b(j,i)
end
end
disp(a);
disp(b);
disp(c);

1 Kommentar

Torsten
Torsten am 23 Mai 2016
Bearbeitet: Torsten am 23 Mai 2016
From what you wrote I can't deduce how you want to get the new matrix from the two given matrices.
Your code from above just calculates C as
C=A.*B.'
I guess this is not what you have in mind.
Best wishes
Torsten.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

John D'Errico
John D'Errico am 23 Mai 2016

0 Stimmen

I'll suggest your mistake is one of definition.
What do you expect when you multiply the elements of the first column with the elements of the first row? In your example, there are 3 products, so that multiplication must result in a vector of length 3.
Oh, do you want to add the elements too? In that case, this is just a matrix multiply.
Taking the columns of matrix a times the rows of matrix b, we get simply:
c = b*a;
Learn to use MATLAB!
Do you wish to compute it using loops for homework? While I don't do your homework, you have made a credible effort.
a=[1 2 3;4 5 6;7 8 9];
b=[1 2 3;4 5 6;7 8 9];
sa = size(a,2);
sb = size(b,1);
c= zeros(sa,sb);
for i=1:sa
for j=1:sb
c(i,j)=dot(a(:,i),b(j,:));
end
end
Note my use of size instead of length. length is dangerous here. (Read the help for length to understand why.) As well, I used a dot product. Finally, see that I preallocated c with zeros. This is important.
Your teacher won't even let you use dot?
a=[1 2 3;4 5 6;7 8 9];
b=[1 2 3;4 5 6;7 8 9];
sa = size(a,2);
sb = size(b,1);
sk = size(a,1);
c= zeros(sa,sb);
for i=1:sa
for j=1:sb
for k = 1:sk
c(i,j)= c(i,j) + a(k,i)*b(j,k);
end
end
end

Weitere Antworten (2)

Roger Stafford
Roger Stafford am 23 Mai 2016

0 Stimmen

If A and B are your two square matrices
C = A.*(B.');
Guillaume
Guillaume am 23 Mai 2016

0 Stimmen

"unfortunately it applys only for (3x3)." The code you've posted applies to any size of matrix. There's is nothing restricting it to 3x3 matrices, so it's not clear why you're asking the question.
Note that you don't need a loop to perform the operation you're carrying out. Have a look at memberwise multiplication .* and transpose .'.

Kategorien

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

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

Start Hunting!

Translated by