フィルターのクリア

How to use a loop to calculate m*n values for an mxn matrix?

6 ビュー (過去 30 日間)
James
James 2013 年 9 月 27 日
編集済み: Jan 2013 年 9 月 27 日
I have two matrices, both approximately 100x100, call them A and B. I am trying to multiply every element of matrix A by every element of matrix B and output these values to a third matrix. In reality, I am doing a little bit more than multiplication, but the operation itself isn't my problem. I am having trouble figuring out how to organize this within a loop.
Any suggestions are greatly appreciated!
  1 件のコメント
Jan
Jan 2013 年 9 月 27 日
As usual it would be helpful, if you post, what you have tried so far an explain, which problems occur.

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

採用された回答

Jan
Jan 2013 年 9 月 27 日
編集済み: Jan 2013 年 9 月 27 日
So you want to multiply 10'000 elements of A with all 10'000 elements of B such that you get 100'000'000 elements as result?
C = zeros(1, 100000000); % 1e8
iC = 0;
for iA = 1:10000
for iB = 1:10000
iC = iC + 1;
C(iC) = A(iA) * B(iB);
end
end
If this is what you are searching for, omitting the inner loop is most likely faster:
B = B(:);
C = zeros(10000, 10000); % 1e8 elements
for iA = 1:10000
C(:, iC) = A(iA) * B;
end
end
And then the relation to BSXFUN is more obvious, but this might be much more complicated in your real case:
C = bsxfun(@times, A(:).', B(:));
If you explain "a little bit more than multiplication" in detail, it would be clear if BSXFUN would be applicable. But perhaps you can use the example as pattern for the more complicated calculations already.

その他の回答 (1 件)

Ilham Hardy
Ilham Hardy 2013 年 9 月 27 日
編集済み: Ilham Hardy 2013 年 9 月 27 日
Is it something like this?
A = [1 2 3 4; 5 6 7 8; 9 10 11 12];
B = [2 2 2 2; 3 3 3 3; 4 4 4 4];
>> C = A.*B
C =
2 4 6 8
15 18 21 24
36 40 44 48
  2 件のコメント
Ilham Hardy
Ilham Hardy 2013 年 9 月 27 日
Sorry, i didn't read your question carefully.
Could you elaborate more on the "a little bit more than multiplication" -part?
Perhaps a simple example of your matrix and the operation?
James
James 2013 年 9 月 27 日
編集済み: James 2013 年 9 月 27 日
Sure, I'll elaborate. I am trying to create two matrices that represent 2 normal planes in 3-space. For every element in the plane of matrix A, I want to "draw" a line to every other element in matrix B and find the angle between this line and the normal to the planes.
My Problem: I need to start with element 1 of matrix A, do this operation, record the value, then move on to element 2 of matrix A and repeat the process until I have operated every element of matrix A on every element of matrix B. This is what I do not know how to do. I know how to do the steps in between, but not how to calculate these values and output them to a new matrix within a loop. Thanks.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by