【问题标题】:MATLAB: get equally spaced entries of VectorMATLAB:获取向量的等距条目
【发布时间】:2013-12-22 22:28:35
【问题描述】:
如何在 MATLAB 中从 Vector 中获取等距的条目,例如我有以下向量:
0 25 50 75 100 125 150
当我选择2时我想得到:
0 150
当我选择3时我想得到:
0 75 150
当我选择4时我想得到:
0 50 100 150
选择1、5 或6 应该不起作用,我什至需要检查if 子句,但我无法弄清楚这一点。
【问题讨论】:
标签:
matlab
vector
distance
space
【解决方案1】:
您可以使用linspace 和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
如果您想强制 n 的值 1、5 或 6 不起作用:测试 n-1 是否除以 length(vector)-1)。如果你这样做,你不需要round 来获取索引:
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
【解决方案2】:
使用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
请注意,除 1 外,无效值会引发错误:
>> 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