Problem array initialization when storing Data
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Réponses (1)
Guillaume
le 11 Nov 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 commentaires
Guillaume
le 11 Nov 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]) = [];
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!