Azzera filtri
Azzera filtri

For loop including zeros in beggining

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Kevin Holly
Kevin Holly il 29 Set 2021
You don't need to create a for loop. You can simply do this:
newY = y(y~=0);
newX = x(y~=0);
  1 Commento
Kevin Holly
Kevin Holly il 29 Set 2021
Modificato: Kevin Holly il 29 Set 2021
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')

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by