For loop including zeros in beggining

5 次查看(过去 30 天)
So I have two 1 by 48 matrices that I'm trying to plot against eachother. The Y vector has zeros at the start and at the end of the data and when plotted against the X I get a parabolic graph, ignoring the zero values off course. I want to eliminate the zeros in Y and they're respective X values using a for that search through the length of the array and stores any non zeros elements in Y in a new vectors and stores the respective X values in a new vector as well in order to be graphed. I've created the for loop below and it eliminates the zeros and the end of Y but not the ones at the start. Is there something I'm doing wrong. Here's the code but with 20 numbers instead of 48. As you can see there are only 10 non-zeros in y but when I run the code newY gives me a 1x15 instead of 1x10 since it includes the first five zeros.
x=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
y=[0 0 0 0 0 1 2 3 4 5 5 4 3 2 1 0 0 0 0 0];
for i=1:20
if y(i)>0
newY(i)=y(i);
newX(i)=x(i);
end
end

采纳的回答

Kevin Holly
Kevin Holly 2021-9-29
You don't need to create a for loop. You can simply do this:
newY = y(y~=0);
newX = x(y~=0);
  1 个评论
Kevin Holly
Kevin Holly 2021-9-29
编辑:Kevin Holly 2021-9-29
If you were to do it as a for loop, I would do it as such:
x=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
y=[0 0 0 0 0 1 2 3 4 5 5 4 3 2 1 0 0 0 0 0];
newY=y;
newX=x;
for i=length(y):-1:1 % You need to go backwards as the indexing will change when we remove values. The array will get shorter.
if y(i)==0
newY(i) = [];% This removes the datapoint from the array
newX(i) = [];
end
end
plot(newX,newY)
xlabel('newX')
ylabel('newY')

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by