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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With