How to perform elementwise multiplication between two matrices with different size or summation between two matrices with the same size
2 ビュー (過去 30 日間)
古いコメントを表示
Hello, imagine I have the following array:
f = 1:10;
x = -22:1:22;
y = -22:1:22;
[u,v] = meshgrid(x,y);
I wish to perform elementwise multiplication operation between 'f' and 'u' (I mean the final array must have numel(f)*numel(u) elements.) . How can I fo this efficiently (definitely I know how to do this using "for loop". this is time consuming.)? Moreover, Imagine that I want to sum "u" and "v" elementwisely which both of them have the same size (so the final array must have numel(u)*numel(v) elements.) . How to do this in order to have high speed?
0 件のコメント
採用された回答
Steven Lord
2023 年 12 月 14 日
Let's look at the sizes of the arrays in question.
f = 1:10;
x = -22:1:22;
y = -22:1:22;
[u,v] = meshgrid(x,y);
whos f x y u v
I wish to perform elementwise multiplication operation between 'f' and 'u' (I mean the final array must have numel(f)*numel(u) elements.)
So do you specifically want the size of the output to be [10 45*45] = [10, 2025]? Since you're using a release that supports implicit expansion this is not that difficult.
A = reshape(f, numel(f), 1).*reshape(u, 1, numel(u));
whos A
How can I fo this efficiently (definitely I know how to do this using "for loop". this is time consuming.)? Moreover, Imagine that I want to sum "u" and "v" elementwisely which both of them have the same size (so the final array must have numel(u)*numel(v) elements.) . How to do this in order to have high speed?
So you want to just normally add u and v?
B = u+v;
whos B
Or do you want to add each element of u to each element of v, not just corresponding elements?
C = reshape(u, numel(u), 1) + reshape(v, 1, numel(v));
whos C
その他の回答 (1 件)
Voss
2023 年 12 月 14 日
f = 1:10;
x = -22:1:22;
y = -22:1:22;
[u,v] = meshgrid(x,y);
whos
Note that u and v are 45x45 matrices, so each has 2025 elements.
Something along these lines may be what you are looking for:
fu = f(:).*u(:).'
uv = u(:)+v(:).'
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!