Reputation: 288010
I want to use a modified version of a variable (without changing the original one) only once, so I don't want to save it in a new variable.
For example:
a = [1 -2 3];
copy = a;
copy(a < 0) = 0;
b = [4 5 6] .* copy;
Can I simplify that to something like the following?
a = [1 -2 3];
b = [4 5 6] .* a(<0 = 0);
Edit:
The example above is just an example. The general problem is how to get the copy
produced by the code below, without creating it.
% `a` is a vector
% `cond` is a logical vector such as `size(a) == size(cond)`
% `num` is a number
copy = a;
copy(cond) = num;
Upvotes: 1
Views: 53
Reputation: 288010
For the general problem
% `a` is a vector
% `cond` is a logical vector such as `size(a) == size(cond)`
% `num` is a number
copy = a;
copy(cond) = num;
Instead of creating copy
, one of the following can be used:
a + (-a+num) .* cond
a .* ~cond + num * cond
Warning: doesn't work if num
is one of the following: nan
, inf
, -inf
(and maybe more)
Performance
It seems that a + (-a+num) .* cond
is faster:
a = rand(1, 10000); cond = a < 0.5; num = 10;
tic; for i=1:100000 a + (-a+num) .* cond; end; toc;
% Elapsed time is 14.764796 seconds.
tic; for i=1:100000 a .* ~cond + num * cond; end; toc;
% Elapsed time is 29.842845 seconds.
Upvotes: 1
Reputation: 112659
You can do it with an anonymous function
which applies the desired modification to your variable:
f = @(x) max(x,0); % this will apply the desired operation to a
a = [1 -2 3];
b = [4 5 6] .* f(a);
The modification required on a
needs to be simple enough, so that it can be defined using an anonymous function. Specifically, according to the above link,
Anonymous functions can contain only a single executable statement.
Upvotes: 0
Reputation: 18488
In this particular case, you can do
b = [4 5 6] .* max(0, a)
But why do you ask this? Do you want to save memory when you do something similar with big matrices? Or do you want to write more compact code?
Upvotes: 2
Reputation: 22519
I don't think the syntax you are looking for exists in Matlab.
Obviously, your real use case might be more complicated than this, but I would change your code to this to remove the extraneous copy
variable:
a = [1 -2 3];
b = [4 5 6] .* a;
b(a < 0) = 0;
See: http://www.mathworks.com/matlabcentral/answers/25235
Upvotes: 0