Extracting the data from a column vector according to mod
5 次查看(过去 30 天)
显示 更早的评论
I have a column vector x. I want to create a vector x1 that are the 1st, 5th, 9th, ... elements of x, x2 that are the 2nd, 6th, 10th elements of x, etc. Please advise how to write a concise code for this task.
0 个评论
回答(3 个)
KL
2018-6-5
Instead of creating multiple variables, why not simply reshape your vector into a matrix?
x = (1:20);
reshape(x,4,[])
ans =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
0 个评论
Basil Saeed
2018-6-5
Given x, you can do:
x1 = x(1:4:length(x))
x2 = x(2:4:length(x))
...
Even more concisely, if you want to extra x1 ... x4, you can do:
for i=1:4
eval(['x' num2str(i) '=x(i:4:length(x))'])
end
0 个评论
Geoff Hayes
2018-6-5
alphedhuez - you could use arrayfun to return a cell array of each of the columns that are parsed (from *x) as per your instructions. For example, suppose
x = (1:100)';
Then we can create your new arrays that are subsets of x as follows
Z = arrayfun(@(k)x(k:4:length(x)), 1:length(x), 'UniformOutput', false);
@(k)x(k:4:50), is an anonymous function that (in this case) takes as input a scalar that we will use to extract data from x starting at index k and then using a step size of four will extract all other data from indices k+4, k+8, ..., 100 (the length of x).
The second input parameter to arrayfun is our k - the starting indices that we wish to extract data from x.
Z{1} will be your column of data extracted from indices 1,5,9,... Z{2} will be your column of data extracted from indices 2,6,10,... etc.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!