Error in Matrix multiplication function.

The message below is the error I get when I run this function file. I am not sure why. The function is supposed give an error if the matrix is not the same size. Any help is appreciated.
Subscript indices must either be real positive integers or logicals.
Error in matrix_multip (line 12)
C(i,j)=A(i,j)*B(i,j);
function [C]=matrix_multip(A,B)
[m,n]=size(A);
[p,q]=size(B);
i=1;
if m~=q || n~=p
disp('Error! Matrices are not same size.')
else
while i<=m
while j<=n
C(i,j)=A(i,j)*B(i,j);
end
end
end

回答 (1 件)

Matt J
Matt J 2015 年 7 月 16 日
編集済み: Matt J 2015 年 7 月 16 日

0 投票

You need to initialize j to 1 (else MATLAB thinks it's sqrt(-1) ) just as you've done for i.
You also need to increment the counters i and j in appropriate places.

3 件のコメント

Walter Roberson
Walter Roberson 2015 年 7 月 16 日
It would make more sense to use "for" instead of "while"
David Hughes
David Hughes 2015 年 7 月 16 日
Thanks for the suggestion. I initialized j then I tried placing i=i+1 & j=j+1 in different locations in the function but it still doesn't work correctly.
Muthu Annamalai
Muthu Annamalai 2015 年 7 月 16 日
Matrix multiplication algorithm in full scalar case needs 3-nested loops.
So in your case you are actually trying to find a dot product, i.e. a sum of products.
So I would rewrite the line
C(i,j)=(A(i,:)*B(:,j));

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeThird-Party Cluster Configuration についてさらに検索

質問済み:

2015 年 7 月 16 日

コメント済み:

2015 年 7 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by