필터 지우기
필터 지우기

comparing arrays without for/while loops

조회 수: 3 (최근 30일)
lp2015
lp2015 2015년 2월 14일
편집: Stephen23 2015년 2월 14일
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

답변 (1개)

Stephen23
Stephen23 2015년 2월 14일
편집: Stephen23 2015년 2월 14일
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
lp2015
lp2015 2015년 2월 14일
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 2015년 2월 14일
편집: Stephen23 2015년 2월 14일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by