大家好我一直在尝试编写这个程序,以寻找一个程序中的最大和最小值。行向量 我在分配他们的维度时遇到了一个问题 指数 我不知道怎么了C和D总是显示为""。1"我是一个初学者,你能不能帮帮我?
function [low,high,index1,index2] = Q1(x)
low = x(1);
high = x(1);
index1 = x(1,2);
index2 = x(1,2);
for i = 2:length(x),
if x(i) < low,
low = x(i);
index1 = find(low);
elseif x(i) > high,
high = x(i);
index2 = find(high);
endif;
endfor;
endfunction
的 index1
和 index2
应以1开头 low
和 high
入手 x(1)
. 当您检测到一个条件时,分配 x(i)
价值和 i
至 relative index
.
function [low,high,index1,index2] = Q1(x)
low = x(1);
high = x(1);
index1 = 1;
index2 = 1;
for i = 2:length(x),
if (x(i) < low)
low = x(i);
index1 = i;
elseif (x(i) > high)
high = x(i);
index2 = i;
endif
endfor;
endfunction
使用随机数据进行测试
octave:1> x=rand(10,1)
x =
0.90588
0.20695
0.46777
0.67169
0.69547
0.24960
0.16570
0.62231
0.18489
0.36467
octave:2> Q1(x)
ans = 0.16570
octave:3> [low,high,index_low,index_high]=Q1(x)
low = 0.16570
high = 0.90588
index_low = 7
index_high = 1
看来你的功能可以在没有循环的情况下快速完成,使用的是 min
和 max
职能。 假设 x
是一个行向量。
>> x = [8 4 9 7 6 4 2 3 5 6]
x =
8 4 9 7 6 4 2 3 5 6
>> [min_x, min_x_loc] = min (x)
min_x = 2
min_x_loc = 7
>> [max_x, max_x_loc] = max (x)
max_x = 9
max_x_loc = 3
如果你想把它放在一个单一的函数中, 使用你的符号,
function [low, high, index1, index2] = Q1(x)
[low, index1] = min (x);
[high, index2] = max (x);
end
(不是必须的,但是使用 end
而不是 endfuntion
保留了matlab的兼容性)