Problem array initialization when storing Data

조회 수: 3 (최근 30일)
Lukas Goldschmied
Lukas Goldschmied 2017년 11월 11일
댓글: Guillaume 2017년 11월 11일
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
Mischa Kim
Mischa Kim 2017년 11월 11일
Please attach the entire code so we can help diagnose.

댓글을 달려면 로그인하십시오.

답변 (1개)

Guillaume
Guillaume 2017년 11월 11일
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
Lukas Goldschmied
Lukas Goldschmied 2017년 11월 11일
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 2017년 11월 11일
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]) = [];

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by