Extracting the data from a column vector according to mod

9 visualizzazioni (ultimi 30 giorni)
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.

Risposte (3)

KL il 5 Giu 2018
Instead of creating multiple variables, why not simply reshape your vector into a matrix?
x = (1:20);
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 il 5 Giu 2018
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))'])

Geoff Hayes
Geoff Hayes il 5 Giu 2018
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.


Scopri di più su Numeric Types in Help Center e File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by