I wish to include or (or any) within a function where the number of arguments (logical vectors) passed in can be more than two and can vary in number. For example, the parent function may create
a=[1;0;0;0]
b=[0;1;0;0]
c=[0;0;0;1]
but the next time may add
d=[0;0;1;0]
how do I get it, in this case, to give me X=[1;1;0;1] the first time around and Y=[1;1;1;1] the second time? The number of vectors could be up to twenty so it would need to be able to recognise how many vectors are being passed in.
A >= B creates the condition greater than or equal. ge( A , B ) is equivalent to A >= B .
The symbols | and || perform different operations in MATLAB®. The element-wise OR operator described here is | . The short-circuit OR operator is || .
For example, I tested arrayfun vs a forloop, squaring the elements, and the speed difference was a factor of two. While this is concrete evidence that we should always use for loops instead of arrayfun, it's obvious that the benefit varies.
This is how I would do it:
function y = f(varargin)
y = any([varargin{:}], 2);
varargin
is a cell array with the function input arguments. {:}
generates a comma-separated list of those arguments, and [...]
(or horzcat
) concatenates them horizontally. So now we have a matrix with each vector in a column. Applying any
along the second dimension gives the desired result.
Since the function contains a single statement you can also define it as an anonymous function:
f = @(varargin) any([varargin{:}], 2);
Example runs:
>> f([1; 1; 0; 0], [1; 0; 0; 1])
ans =
4×1 logical array
1
1
0
1
>> f([1; 1; 0; 0], [1; 0; 0; 1], [0; 0; 1; 0])
ans =
4×1 logical array
1
1
1
1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With