필터 지우기
필터 지우기

For loop including zeros in beggining

조회 수: 1 (최근 30일)
Robert Munoz
Robert Munoz 2021년 9월 29일
편집: Kevin Holly 2021년 9월 29일
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