Use two bsxfun for row and column vector to span matrix without putting in memory
1 view (last 30 days)
Show older comments
Hello, I have a vector A of size 1xN and a vector B of size MxN I can span a MxN matrix temp with temp=bsxfun(@times,A,B);. Now the tricky part. I create this temp matrix to multiply the following to my data matrix:
data=data.*exp(1i.*temp);
Is there a way I can use bsxfun to directly apply this operation on data, without creating the large temp matrix in the memory?
Thanks
1 Comment
dpb
on 29 Sep 2017
bsxfun created the temp in memory behind scenes anyway, so it didn't actually save memory in computation, just was transparent in not having the explicit temp variable.
Beginning w/ R2016b implicit expansion was introduced that will replace most uses of bsxfun with more efficient memory usage. If you have a release of that vintage or newer investigate that feature.
Answers (1)
Jan
on 30 Sep 2017
A = rand(1, 1e5);
B = rand(100, 1e5);
data = ones(size(B));
tic, for k = 1:5
temp = bsxfun(@times, A, B);
data = data .* exp(1i .* temp);
end, toc
tic, for k = 1:5
temp = bsxfun(@times, 1i * A, B);
data = data .* exp(temp);
end, toc
tic, for k = 1:5
data = data .* exp((1i * A) .* B); % Auto-expanding in >= R2016b
end, toc
Elapsed time is 2.421372 seconds.
Elapsed time is 2.857152 seconds.
Elapsed time is 2.136714 seconds.
Observation from the profiler:
data = data .* exp(1i .* temp);
takes the same time as
data = data .* exp(temp);
but
temp = bsxfun(@times, 1i * A, B);
or
temp = 1i * bsxfun(@times, A, B);
have 100% more runtime than
temp = bsxfun(@times, A, B);
If this piece of code is the bottleneck of your code, create C-Mex function.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!