如何在不使用 min 或专门制作的函数的情况下找到最小值
How to find a minimum value without using min or specifically made functions
function [c] = nextinteger(v)
c=0;
a =0;
h=[0];
for i= 1:length(v)
if v(i)>0
h=v;
if h(i+1)>h(i)
a = h(i);
c=a+1;
end
end
end
end
我必须"Write a function nextinteger(v)
which takes as input a vector v
and as output returns the smallest positive integer which does not appear in v
."
目前我似乎找不到解决方案,上面的代码是我所能找到的解决方案。谁能告诉我我需要考虑什么以及我需要修复什么才能更接近我的解决方案
期望结果示例:
如果输入是
[1, 2, 3]
,输出将是
4
如果输入是
[4, 0, 1, -10],
输出将是
2
示例输入
v=[10 0 1 -1 3 4 5];
n=length(v); % length of input
tmp=1:n; % possible integer numbers
for k=1:n % loop over vector
comp_value=v(k);
for r=1:length(tmp) %loop over reference
if tmp(r)==comp_value %compare
tmp(r)=[]; %eclude
break
end
end
end
if isempty(tmp) % check whether all numbers are gone
result=n+1;
else
result=tmp(1);
end
输出:
result =
2
function [c] = nextinteger(v)
c=0;
a =0;
h=[0];
for i= 1:length(v)
if v(i)>0
h=v;
if h(i+1)>h(i)
a = h(i);
c=a+1;
end
end
end
end
我必须"Write a function nextinteger(v)
which takes as input a vector v
and as output returns the smallest positive integer which does not appear in v
."
目前我似乎找不到解决方案,上面的代码是我所能找到的解决方案。谁能告诉我我需要考虑什么以及我需要修复什么才能更接近我的解决方案
期望结果示例: 如果输入是
[1, 2, 3]
,输出将是
4
如果输入是
[4, 0, 1, -10],
输出将是
2
示例输入
v=[10 0 1 -1 3 4 5];
n=length(v); % length of input
tmp=1:n; % possible integer numbers
for k=1:n % loop over vector
comp_value=v(k);
for r=1:length(tmp) %loop over reference
if tmp(r)==comp_value %compare
tmp(r)=[]; %eclude
break
end
end
end
if isempty(tmp) % check whether all numbers are gone
result=n+1;
else
result=tmp(1);
end
输出:
result =
2