フィルターのクリア

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 Center および File ExchangeLoops 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