comparing arrays without for/while loops

10 views (last 30 days)
lp2015
lp2015 on 14 Feb 2015
Edited: Stephen23 on 14 Feb 2015
I need to compare 2 arrays given as inputs to a function, without using for/while loops. The function should get two arrays as inputs (can be any form - vector/mat/integer) and return one output element - an equal sized array, where every (i,j) element is the bigger (i,j) element from both inputs, or 0 if they are equal. If input arrays are not equal size output should be an empty array. I tried using recursion , but can't find a good solution. If evey time I'll call the function with (row-1,col-1), I'll get only the main Diagonal. Also I have a problem of array indicies. I thougt maybe using (end-1) but I have a problem when end=1. Any ideas? Thanks

Answers (1)

Stephen23
Stephen23 on 14 Feb 2015
Edited: Stephen23 on 14 Feb 2015
You could start with something like this:
function [out,idx] = myfun(A,B)
out = [];
idx = [];
sza = size(A);
szb = size(B);
if numel(sza)==numel(szb) && all(sza==szb)
out = max(A,B);
idx = A==B;
end
I have not included your requirement that array value is 0 if two corresponding values are the same: this loses information (eg it cannot distinguish between two values being the same, and max value is zero). It is likely to be faster and neater code if you keep these two concepts distinct. It also directly conflicts with standard practice of using 0 for false and 1 for true.
  2 Comments
lp2015
lp2015 on 14 Feb 2015
Thanks, This is a great and simple answer, The only problem is that equal elements will not be 0 in the output matrix. Every (i,j) place that is equal in both inputs should be a 0 in the output. Thanks.
Stephen23
Stephen23 on 14 Feb 2015
Edited: Stephen23 on 14 Feb 2015
If your really want those output elements to be zero, then add this line immediately before the end of the if statement:
out(idx) = 0;
But really it would probably be best to keep the max and equality concepts distinct: How would you be able to tell the difference between max(-1,0) and 3==3, as both would give zero in your output?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!