How do I select and/or delete values of a certain index in an array?
14 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Nick
on 7 Apr 2017
Edited: Nick
on 7 Apr 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
0 Comments
More Answers (1)
Image Analyst
on 7 Apr 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.
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!