Function won't index properly

13 次查看(过去 30 天)
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?

采纳的回答

Andrei Bobrov
Andrei Bobrov 2011-11-6
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 个评论
Ammar
Ammar 2011-11-8
Brilliant. The first method worked perfectly. (I never tried the second one.) Never would have come up with this on my own.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by