How do you compute the product of a matrix and each column of another matrix without a for loop in MATLAB, or is this just not possible?

2 ビュー (過去 30 日間)
A 4x14 matrix (C) is multiplied by each column of a 14xN matrix (x) - hence by N individual 14 element column vectors - to form N individual 4 element column vectors - represented by a 4xN matrix (y) -, where N is a known yet large number, let's assume N = 132 for simplicity.
I use a for loop for this operation:
N = 132;
C = [0,1,0,0,0,0,0,0,0,-1,0,-0.68,0, 1.53;
0,0,0,1,0,0,0,0,0,-1,0,-0.64,0,-1.92;
0,0,0,0,0,1,0,0,0,-1,0, 0.86,0,-1.92;
0,0,0,0,0,0,0,1,0,-1,0, 0.91,0, 1.53];
x = rand(14,N);
for n = 1:N
y(:,n) = C*x(:,n);
end
y
y = 4x132
0.8171 0.6519 -0.1231 -0.3986 0.0067 0.5236 0.5635 -0.0142 -0.1589 0.7049 0.0493 0.8107 0.0467 0.3760 0.1629 -0.5810 -0.0014 0.0753 0.1952 0.9694 0.9893 1.0198 0.3636 1.1546 -0.1246 0.2960 0.6670 1.2503 0.7362 0.3130 -1.5713 -0.2918 -2.0231 -1.5203 -0.4916 -1.5073 -0.6379 -1.3672 -1.6384 -2.3884 -1.0684 -1.7009 -1.4159 -1.6700 -0.7916 -0.8800 -0.6646 -0.3746 -1.3475 -0.9698 -2.3454 -0.8660 -1.2379 -1.0661 -2.0218 -0.7671 -1.8403 -1.7703 -1.3348 -1.1637 -0.7278 -0.1535 -0.8238 -0.5070 0.4447 -0.4600 -0.1615 0.2374 -1.0285 -1.2346 -0.3279 -0.5324 0.3478 -1.8978 0.6776 -0.8982 0.0732 -0.0802 0.0912 -0.1890 -2.0549 -1.3461 -1.2515 -0.6147 -1.0407 -1.1961 -1.0804 -1.5745 0.1213 -0.2728 1.0967 1.6059 1.5573 0.2685 1.8956 1.9566 1.2679 1.4401 0.3141 2.0937 0.3331 1.9022 1.2138 1.1691 1.4234 0.3172 0.7299 -0.4859 1.4454 0.6288 1.6082 1.1965 1.0090 2.0954 1.3740 0.2839 1.4502 2.1792 1.8181 0.8593
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
This works fine, however, I wondered how this operation could be implemented without a for loop in MATLAB - all variables in the loop are available prior to the first iteration - to utilize MATLAB's matrix multiplication optimization and thus improve runtime performance, or is this just not possible?
Thanks in advance for any help!

採用された回答

Torsten
Torsten 2024 年 7 月 4 日
  1 件のコメント
Simon
Simon 2024 年 7 月 4 日
Oh ... When I implemented the multiplication like that prior to posting the question, MATLAB responded with 'Arrays have incompatible sizes for this operation' and I couldn't figure out why. Because of your answer I tried again and just realized that this error message actually concerned the next line. Now, I honestly feel a little bit embarrassed to having asked such a question. Nonetheless, thank you for your answer and for making me realize the bug! I think I should take a break.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by