Info

此问题已关闭。 请重新打开它进行编辑或回答。

I have an array of data [ 1.1 0.5 1.8 2.5 5.0 4.2 3.3 4.8 2.5] After the first number (1.1) need pick the next higher number which is 1.8 until until you get to the peak (5.0) then pick the number in descending order from the peak to the lowest

1 次查看(过去 30 天)
I have an array of data [ 1.1 0.5 1.8 2.5 5.0 4.2 3.3 4.8 2.5] After the first number (1.1) I need to pick the next higher number which is 1.8 until you get to the peak (5.0) then pick the number in descending order from the peak again by picking the next next lower number after 5.0 which is 4.2 follow by 3.3 then drop 4.8 because is increasing not decreasing until you get to the last number which is 2.5. how to code this
  6 个评论
Selby
Selby 2017-8-13
Oh I see! Sorry for confusion. I didn't read your comment fully this should work better.
dat = [ 1.1 0.5 1.8 2.5 5.0 4.2 3.3 4.8 2.5];
[max_value,max_position] = max(dat);
first_part = [dat(1)];
current_highest = dat(1);
for i=2:max_position
if dat(i)> current_highest
first_part = [first_part dat(i)];
current_highest = dat(i);
end
end
last_part = [];
current_lowest = max_value;
for i=max_position+1:length(dat)
if dat(i)< current_lowest
last_part = [last_part dat(i)];
current_lowest = dat(i);
end
end
answer = [first_part last_part];

回答(2 个)

Jan
Jan 2017-8-11
x = [1.1 0.5 1.8 2.5 5.0 4.2 3.3 4.8 2.5];
% Find the maximum at first:
[v, idx] = max(x);
% Then run two loops to filter out the cumulative maximum/minimum:
result = zeros(1, numel(x)); % Pre-allocate
result(1) = x(1);
c = 1;
for k = 2:idx
if x(k) > result(c)
c = c + 1;
result(c) = x(k);
end
end
for k = idx+1:numel(x)
if x(k) < result(c)
c = c + 1;
result(c) = x(k);
end
end
result = result(1:c); % Crop unused elements

Andrei Bobrov
Andrei Bobrov 2017-8-13
编辑:Andrei Bobrov 2017-8-13
data = [1.1 0.5 1.8 2.5 5.0 4.2 3.3 4.8 2.5];
[~,ix] = max(data);
ii = false(size(data));
r = data(1);
for jj = 1:numel(data)
if jj <= ix && r <= data(jj)
ii(jj) = true;
r = data(jj);
elseif jj >= ix && r >= data(jj)
ii(jj) = true;
r = data(jj);
end
end
out = data(ii)

此问题已关闭。

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by