how to create vector In for/if cyklus?

5 次查看(过去 30 天)
Hy , I would like to create maxim vector what is should contain the numbers, when the if is true,then the index of the number it was saven in the empty maxim vector...the if is 3 times is true in for cyklus but the output is , always rewrite the before value what was in the maxim
maxim = [];
for i=2:80
if (y(i-1)<y(i) && y(i+1)<y(i))
for j=1:(j+1)
maxim(j) = y(i)
end
end
end
y1 = maxim(1)
y2 = maxim(2)

采纳的回答

Geoff Hayes
Geoff Hayes 2015-11-21
xy - it seems as if your code is iterating over the y array and looking for those elements which are a maximum with respect to its neighbours
if (y(i-1)<y(i) && y(i+1)<y(i))
When this is true, what do you want to save: that maximum value or its index into y? If the former, then you should be saving y(i) and if the latter, then you should be saving i. Something like
maximumValues = [maximumValues y(i)]; % (1)
or
maximumIdcs = [maximumIdcs ; i] % (2)
where we have initialized either array to the empty matrix (like you have done for maxim). Either of the above would replace your code
for j=1:(j+1)
maxim(j) = y(i)
end
which I don't quite follow. The above iterates from 1 to j+1, replacing the first j+1 elements of maxim with the same y(i). This is why your maxim array has identical values...because they are getting reset (or initialized) to same y(i). I think that you just need to replace this with (1) or (2) from above and you will be have what you are looking for.
As an aside, it is better to not use i and j as indexing variables as MATLAB uses both of these to represent the imaginary number.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Compiler 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by