Effacer les filtres
Effacer les filtres

How do I select and/or delete values of a certain index in an array?

17 vues (au cours des 30 derniers jours)
Emily22
Emily22 le 7 Avr 2017
I have a data set (OrbSolPwr) in a 2880 x 1 double array. I only want the first (n) terms. How do I either select the first (n) terms into a new array or delete the (n+1):numel(OrbSolPwr) terms? (Using the R2016a student/academic version)
n = 1261;
m = numel(OrbSolPwr); % m = 2880
for i = 1:m;
if i > n:
OrbSolPwr(i,1) = [];
end
end
First try gives the error that a null assignment can have only one con-colon index for line 5 above. I realize that the index would also get messed up since the length will change as the data set shrinks, but I don't know how to write that.
n = 1261;
m = numel(OrbSolPwr); % m = 2880
for i = n+1:m;
OrbSolPwr(i,1) = [];
end
I also tried this, which gives the same error as before.

Réponse acceptée

Nick
Nick le 7 Avr 2017
Modifié(e) : Nick le 7 Avr 2017
This is how you would extract the data to a new array
%Generate random numbers for Example
OrbSolPwr = randi(10,2880,1);
%Select cutoff
n = 15;
newOrbSolPwr = zeros(n,1);
%Extract values from old data to new data
for i = 1:n
newOrbSolPwr(i) = OrbSolPwr(i);
end
if you wanted to delete the elements. The index will keep shrinking but its ok because we are iterating by a negative 1 so it won't exceed the matrix dimensions
m = numel(OrbSolPwr)
for i = m:-1:n+1
OrbSolPwr(i) = [];
end

Plus de réponses (1)

Image Analyst
Image Analyst le 7 Avr 2017
Nick's solution is like what you'd do in C or Java, not MATLAB. In MATLAB, you simply do it in one line of code by extracting the rows you want:
OrbSolPwr = OrbSolPwr(1:n);
Any elements after n are discarded. No for loop is needed at all because MATLAB is a vectorized language.

Catégories

En savoir plus sur Matrix Indexing 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!

Translated by