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

24 次查看(过去 30 天)
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.

采纳的回答

Nick
Nick 2017-4-7
编辑:Nick 2017-4-7
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

更多回答(1 个)

Image Analyst
Image Analyst 2017-4-7
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.

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by