Extracting the data from a column vector according to mod
2 ビュー (過去 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 で Matrices and Arrays についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!