Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: get equally spaced entries of Vector

How would it be possible to get equally spaced entries from a Vector in MATLAB, e.g. I have the following vector:

 0    25    50    75   100   125   150

When I chose 2 I want to get:

0   150

When I chose 3 I want to get:

0   75   150

When I chose 4 I want to get:

0   50   100   150

Chosing 1, 5 or 6 shouldn't work and I even need a check for an if-clause for that but I can't figure this out.

like image 916
tim Avatar asked Feb 14 '23 14:02

tim


2 Answers

You can generate the indices with linspace and round:

vector = [0    25    50    75   100   125   150]; % // data
n = 4; % // desired number of equally spaced entries

ind = round(linspace(1,length(vector),n)); %// get rounded equally spaced indices
result = vector(ind) % // apply indices to the data vector

If you want to force that values 1, 5 or 6 for n don't work: test if n-1 divides length(vector)-1). If you do that you don't need round to obtain the indices:

if rem((length(vector)-1)/(n-1), 1) ~= 0
    error('Value of n not allowed')
end
ind = linspace(1,length(vector),n); %// get equally spaced indices
result = vector(ind) % // apply indices to the data vector
like image 99
Luis Mendo Avatar answered Feb 24 '23 10:02

Luis Mendo


Use linspace:

>> a
a =

     0    25    50    75   100   125   150

>> a(linspace(1,length(a),4))
ans =

     0    50   100   150

>> a(linspace(1,length(a),3))
ans =

     0    75   150

>> a(linspace(1,length(a),2))
ans =

     0   150

Note that, except for 1, the invalid values raise an error:

>> a(linspace(1,length(a),5))
error: subscript indices must be either positive integers or logicals
>> a(linspace(1,length(a),6))
error: subscript indices must be either positive integers or logicals
like image 34
damienfrancois Avatar answered Feb 24 '23 09:02

damienfrancois