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!