Reputation: 323
I'm a Matlab newbie and I would like to assign NaN values to an array of size(j, k, l) wherever the dimension is j < k or j < l. How do I do this most efficiently?
Upvotes: 2
Views: 178
Reputation: 15837
You can use bsxfun
to do it efficiently:
J = (1:size(A,1)).';
K = 1:size(A,2);
L = reshape(1:size(A,3),1,1,[]);
A(bsxfun(@or,bsxfun(@lt,J,K),bsxfun(@lt,J,L))) = NaN;
In MATLAB r2016b or Octave you can simply write:
J = (1:size(A,1)).';
K = 1:size(A,2);
L = reshape(1:size(A,3),1,1,[]);
A(J<K|J<L)=NaN;
Result of a test on a matrix A = rand(500,400,300)
:
________________________________
| METHOD | MEMORY | SPEED |
|==========|==========|==========|
| MESHGRID | 1547 MB | 1.24 Secs|
|----------|----------|----------|
| BSXFUN | 57 MB | 0.18 Secs|
|__________|__________|__________|
Upvotes: 4
Reputation: 35525
Use fancy vecotization:
% this may be memory expensive for big matrices:
[j,k,l]=meshgrid(1:size(A,1),1:size(A,2),1:size(A,3));
% Tada!
A(j<k | k<l)=NaN;
If you do not have enough RAM (or do not want to use it for this), then the best option is just loopy:
for jj=1:size(A,1)
for k=1:size(A,2)
for l=1:size(A,3)
if (jj<k | k<l)
A(jj,k,l)=NaN;
end
end
end
end
This will likely be slower, but doesn't need any extra memory.
Upvotes: 3