Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying "or" function to more than two vectors Matlab

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.

like image 468
Mary Avatar asked Oct 24 '17 16:10

Mary


People also ask

How do you use greater than function in MATLAB?

A >= B creates the condition greater than or equal. ge( A , B ) is equivalent to A >= B .

What is the or symbol in MATLAB?

The symbols | and || perform different operations in MATLAB®. The element-wise OR operator described here is | . The short-circuit OR operator is || .

Is Arrayfun faster than for loop?

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.


1 Answers

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
like image 132
Luis Mendo Avatar answered Sep 24 '22 13:09

Luis Mendo