Function won't index properly

13 Ansichten (letzte 30 Tage)
Ammar
Ammar am 6 Nov. 2011
I have created the following function to find the index numbers of the elements of array a that are less than or equal to b, whether be is a scalar or another array of length(a)=length(b).
function [m,k]=my_find(a,b)
for i=1:length(a)
if length(b)==1
k(i)=(a(i)<=b);
if k==1
m=i;
end
elseif length(b)==length(a)
k(i)=(a(i)<=b(i));
if k==1
m=i;
end
else
disp('Error')
end
end
disp('m = '),disp(m)
disp('k = '),disp(k)
For some reason, the m value does not index properly, even though the k value returns the proper values. The m value if supposed to replace the use of the find function. Any suggestions?

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 6 Nov. 2011
function [m, k] = Ammar_find(a,b)
na = numel(a);
nb = numel(b);
if nb ~= na && nb > 1,
disp('size "a" and "b" are not consistent');
m = [];
k = [];
else
k = a <= b;
m = nonzeros(k.*reshape(1:na,size(a)));
end
variant
function [m, k] = Ammar_find(a,b)
try
k = a <= b;
m = nonzeros(k.*reshape(1:na,size(a)));
catch err
rethrow(err);
end
  1 Kommentar
Ammar
Ammar am 8 Nov. 2011
Brilliant. The first method worked perfectly. (I never tried the second one.) Never would have come up with this on my own.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays 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!

Translated by