How to perform elementwise multiplication between two matrices with different size or summation between two matrices with the same size
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Steven Lord
on 14 Dec 2023
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
More Answers (1)
Voss
on 14 Dec 2023
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(:).'
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!