What is wrong with my code short simple function using only - if,for,length and variables)?
1 次查看(过去 30 天)
显示 更早的评论
I needed to write a function that uses only if for length and variables and calls another function - valFind(that runs very well-added below), my function gets:1) a vector 2)an arrays of numbers to search for and brings back the first places in which those numbers appear in the vector (or 0 if they don't appear) for example:
% code
a=[2 4 6 8 4 2]
b=[2 8 9]
c=valFindAll(a,b) --> [1 4 0]
this is valFind (runs fine the problem is in the text function)
% code
function [result] = valFind(a,b)
result = [];
for ii=1:length(a)
if a(ii) == b
result = [result ii];
end
end
this is the function that (I don't know why) doesn't run
% code
function [resultVec] = valFindAll(a,v)
resultVec =[];
for ii=1:length(v)
[result]=valFind(a,v(ii));
if result == []
resultVec = [resultVec 0];
else
resultVec = [resultVec result(1)];
end
end
0 个评论
采纳的回答
Huseyin Kaya
2013-12-15
编辑:Huseyin Kaya
2013-12-15
Just change
result == []
with
length(result) == 0
and everything will work fine.
更多回答(1 个)
Jan
2013-12-15
You can use isempty(result) instead of result == [].
Another more efficient method:
function [resultVec] = valFindAll(a,v)
resultVec = zeros(1, length(v));
for ii = 1:length(v)
result = valFind(a,v(ii)); % No brackets around left hand side
if ~isempty(result)
resultVec(ii) = result;
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!