Problem array initialization when storing Data

3 visualizaciones (últimos 30 días)
Lukas Goldschmied
Lukas Goldschmied el 11 de Nov. de 2017
Comentada: Guillaume el 11 de Nov. de 2017
I red in some Data and stored it in a vector(A). Now I want to delet the first 200 entrys. I'm using a for loop for that. Strangely, I get the error: Matrix index is out of range for deletion. So when I look for the lenght of my 2 vectors, one is just half the length of the other:
fname = tabularTextDatastore('curves.dat');
L = read(fname);%3 values all separated by a space bar
x = L(:,3);%vector with values of column3
y = L(:,2);%vector with values of column2
z = L(:,1);vector with values of column1
q = linspace(0,99,100);
A = table2array(x)
W = A;
for i=1:200
W(i) = [];
end
W
q1 = q(:);
%plot(q1,A)
Can somebody pleas explain me, why W has not the same length as A?
  1 comentario
Mischa Kim
Mischa Kim el 11 de Nov. de 2017
Please attach the entire code so we can help diagnose.

Iniciar sesión para comentar.

Respuestas (1)

Guillaume
Guillaume el 11 de Nov. de 2017
I want to delet the first 200 entrys. I'm using a for loop for that.
Always a bad idea. Most beginners never implement that properly
for i=1:200
W(i) = [];
end
So, at i = 1, you delete the first element. So far so good. After that deletion, what was element 2 is now element 1, what was element 3 is now 2, etc.
Next step, i = 2. You delete the element at that index, but that element is what was element 3. So far, you've deleted element 1 and 3. What was element 2 is still 1, what was element 4 is now 2, what was element 5 is now 3, etc.
Next step, i = 3. You delete the element at that index. That was element 5. You get the picture. It's not working at all.
Don't use loops for deletion, particularly as there's a much simpler way:
W(1:200) = []; %delete first 200 elements in one go
  2 comentarios
Lukas Goldschmied
Lukas Goldschmied el 11 de Nov. de 2017
Thanks for your help! That makes total sense. So with your way of deletion, I can also delet the last 200 elemets by typing:
W(100:300) = [];
and delet the first 100 and the last 100 by typing:
W(1:100)=[];
W(100:200) = [];
Guillaume
Guillaume el 11 de Nov. de 2017
Note that 100:300 is 201 elements, not 200.
W(101:300) = [];
will indeed delete the last 200 elements of W if and only if W has 300 elements. To be guaranteed to delete the last 200 elements regardless of the number of elements in W:
W(end-199:end) = [];
To delete the first 100 and last 100 regardless of the number of elements:
W([1:100, end-99:end]) = [];

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by