comparing arrays without for/while loops
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Antworten (1)
Stephen23
am 14 Feb. 2015
Bearbeitet: Stephen23
am 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 Kommentare
Stephen23
am 14 Feb. 2015
Bearbeitet: Stephen23
am 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?
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!