根据其内容将矢量拆分为几个向量

时间:2015-06-18 15:30:16

标签: arrays matlab vector

我知道一个向量将包含值100,200和400.这些值不会混淆,而是顺序,例如

target = [100 100 100 100 200 200 400 400 400];

我想将此向量拆分为三个向量,每个向量包含该类型的所有值。

A = [100 100 100 100];
B = [200 200];
C = [400 400 400];

目标的长度会不时变化,因此比例为100,200和400.

如何以简单的方式进行拆分?

我自己的解决方案看起来像这样,但我认为还有另一种方法需要更少的代码。

columns = size(target, 2);

A = [];
B = [];
C = [];
% Splitting target into groups
for j = 1:columns
    if target(1, j) == 100
        A = [A, 100];
    elseif target(1, j) == 200
        B = [B, 200];
    elseif target(1,j) == 400
        C = [C, 400];
    end
end

4 个答案:

答案 0 :(得分:3)

更简单:

target=[100 100 100 100 200 200 400 400 400];

A = target(target==100)
B = target(target==200)
C = target(target==400)

如何工作:target==x返回大小等于target的逻辑数组。然后,您可以使用该逻辑数组来索引target

答案 1 :(得分:3)

更通用的方法:

%// find and count unique elements
[a,b] = hist(target,unique(target));

%// Create vectors according to target and number occurences and store them in cell array
temp = arrayfun(@(x,y) y*ones(x,1),a,b,'uni',0)

另一种可能更快的方法是:

%// get indices of unique values
[~,~,c] = unique(target)
%// Create vectors according to indices and store them in cell array
temp = accumarray(c(:),target(:),[],@(x) {x})

我个人会建议您在此时停止并继续使用单元格阵列!

如果您知道有多少独特元素,并且确实想将它们存储在单独的变量中,您可以使用:

[A,B,C] = temp{:}

我能想到的最通用且容易出错的方法是:

%// create a map container with all values you're expecting and it's corresponding specifier
valueSet =   {'A', 'B', 'C'};
keySet = [100 200 400];
mapObj = containers.Map(keySet,valueSet)

%// create a struct and distribute keys to specifier
for ii = 1:numel(keySet);
   out.(mapObj(keySet(ii))) = target(target == keySet(ii));
end

您获得的结构out包含字段ABC

有趣的是,您还可以自动生成keySetvalueSet

%// keySet are all unique values of target
keySet = unique(target)
%// create specifiers according to number of unique elements
valueSet = cellstr(char(65:65+numel(keySet)-1).') %'
%// you get 'A' 'B' and 'C' to use as field names

通过这种方式,您不需要知道您的元素和实际拥有的元素数量。与原始请求的唯一区别在于,您无法获取变量ABC,但out.Aout.B和{{ 1}}

enter image description here

答案 2 :(得分:2)

以下是使用difffind进行此操作的方法。

clear
clc
close all

target=[100 100 100 100 200 200 400 400 400];

%// Form vector containing cumulative differences from consecutive elements
DiffVector = [-Inf diff([target Inf])];

DiffVector看起来像这样:

DiffVector =

  -Inf     0     0     0   100     0   200     0     0   Inf


%// Find where values are not equal to 0. That's the starting indices of
%each sequence of numbers of interest.
indices = find(DiffVector~=0)

indices看起来像这样:

indices =

     1     5     7    10

%// Put every sequence in its own cell.
v = cell(1,numel(indices)-1);
for k = 1:numel(indices)-1
    v{k} = target(indices(k):idx(k+1)-1);
end

显示单元格数组的内容

celldisp(v)

v{1} =

   100   100   100   100



v{2} =

   200   200



v{3} =

   400   400   400

为简单起见,您可以将前两个步骤合并为一个步骤。

耶!

答案 3 :(得分:1)

另一种方法:使用mat2cell排序然后拆分成单元格:

st = sort(target);
result = mat2cell(st, 1, diff([0 find(diff(st)) numel(st)]));