Extracting the data from a column vector according to mod

조회 수: 6 (최근 30일)
alpedhuez
alpedhuez 2018년 6월 5일
답변: KL 2018년 6월 5일
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.

답변 (3개)

KL
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

Basil Saeed
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

Geoff Hayes
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.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by