Matrixes not multiplying correctly using for loops

I have two matrixes (3x4 and 4x3) that I'm trying to multiply with the use of if and for loops, but it appears there is an issue with the indexing of the matrixes. The problem contains code meant to check the dimensions of each matrix and ensure that the column count of the first matrix is equal to the row count of the second matrix. However, when I run the code, it gives me an error of "Index in position 2 exceeds array bounds. Index must not exceed 3". Is there an issue in the for loop that is perhaps messing with the multiplication?
af = [ af '.txt' ] ; a = load(af) ; [n,m] = size(a) ;
bf = [ bf '.txt' ] ; b = load(bf) ; n1 = size(b,1) ; m1 = size(b,2) ;
if n ~= m1
error('incorrect dimensions (rows)') ;
end
if m ~= n1
error('incorrect dimensions (columns)') ;
end
c = zeros(n,m) ;
for i = 1 : n
for j = 1 : m
c(i,j) = a(i,j) * b(i,j) ;
end
end
disp(c)

4 件のコメント

Stephen23
Stephen23 2024 年 3 月 19 日
編集済み: Stephen23 2024 年 3 月 19 日
"Is there an issue in the for loop that is perhaps messing with the multiplication?"
There is an issue, and the error message tells you exactly what it is: you are trying to index into elements that do not exist.
Let us presume that a has size 3x4 and b has size 4x3. This would mean m=4, which means j iterates from 1 to 4. But what do you expect to happen when you try to indexing like this b(i,j) when j=4 but b only has 3 columns?
Note that matrix multiplication is fundamentally about repeated sums, and that is not reflected in your algorithm.
Mason Reilly
Mason Reilly 2024 年 3 月 20 日
so should b(i,j) be swapped to b(j,i) to account for it being 4x3 instead of 3x4?
Torsten
Torsten 2024 年 3 月 20 日
The element (i,j) of C = A*B is given by
sum_k (a_ik * b_kj)
Do you think that
for i = 1 : n
for j = 1 : m
c(i,j) = a(i,j) * b(i,j) ;
end
end
will give a result for c(i,j) that is equivalent to that sum ?
Chuguang Pan
Chuguang Pan 2024 年 3 月 20 日
The matrix multiplication is , suppose that the size of a is [n m], the size of b is [m p], the size of c is [n p].

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

回答 (2 件)

Matt J
Matt J 2024 年 3 月 20 日
編集済み: Matt J 2024 年 3 月 20 日

1 投票

[n,w]=size(a);
[h,m]=size(b);
assert(w==h,'Inner dimensions incompatible')
c=zeros(n,m);
for i = 1 : n
for j = 1 : m
c(i,j) = a(i,:) * b(:,j) ;
end
end
Catalytic
Catalytic 2024 年 3 月 20 日

1 投票

One loop -
[n,w]=size(a);
[h,m]=size(b);
if w~=h
error('Inner dimensions do not agree.')
end
c=0;
for k = 1 : w
c = c + a(:,k).*b(k,:);
end

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2024 年 3 月 19 日

回答済み:

2024 年 3 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by