开发者

matlab: represent 1 column data into 3 column data

if 1st column detect 1, then add  1 -1 -1 to 2nd to 4th column 
if 1st column detect 2, then add -1  1 -1 to 2nd to 4th column 
if 1st column detect 3, then add -1 -1  1 to 2nd to 4th column 

example: A is 5x1 matrix

A=
1
2
3
2
1

i would like to get the result as below: A 开发者_JAVA技巧become 5x4 matrix

A =
1  1 -1 -1
2 -1  1 -1
3 -1 -1  1
2 -1  1 -1
1  1 -1 -1

the code i wrote below can not get the above result, please help...

if A(1:end,1) == 1
   A(1:end,2:4) = [1 -1 -1]
else if A(1:end,1) == 2
   A(1:end,2:4) = [-1 1 -1]
else 
   A(1:end,2:4) = [-1 -1 1]
end


You can simply use indexing:

V = [
  1 -1 -1    %# rule 1
 -1  1 -1    %# rule 2
 -1 -1  1    %# rule 3
];

A = [1;2;3;2;1];

newA = [A V(A,:)];

The result:

newA =
     1     1    -1    -1
     2    -1     1    -1
     3    -1    -1     1
     2    -1     1    -1
     1     1    -1    -1


Firstly, you're comparing integers to vectors in your if statements. That won't work. You need to loop over the entire vector, checking each element by itself. It is also preferable to preallocate the result matrix before modifying it, as allocation is an expensive operation:

A = [A zeros(size(A,1), 3)];
for i=1:size(A,1)
    if(A(i,1) == 1)
        A(i,2:4) = [1 -1 -1];
    elseif(A(i,1) == 2)
        A(i,2:4) = [-1 1 -1];
    elseif(A(i,1) == 3)
        A(i,2:4) = [-1 -1 1];
    end
end


This should give you an idea

>>> A= [1 2 3 2 1; zeros(3, 5)]';
>>> m= 1== A(:, 1); A(m, 2: 4)= repmat([ 1 -1 -1], sum(m), 1);
>>> m= 2== A(:, 1); A(m, 2: 4)= repmat([-1  1 -1], sum(m), 1);
>>> m= 3== A(:, 1); A(m, 2: 4)= repmat([-1 -1  1], sum(m), 1);
>>> A
A =
   1   1  -1  -1
   2  -1   1  -1
   3  -1  -1   1
   2  -1   1  -1
   1   1  -1  -1

how to, quite straightforward manner, encapsulate this kind of functionality in to your code.

For example like

>>> A= [1 2 3 2 1; zeros(3, 5)]';
>>> I= [1 -1 -1; -1 1 -1; -1 -1 1];
>>> for k= 1: size(I, 1)
  >    m= k== A(:, 1); A(m, 2: 4)= repmat(I(k, :), sum(m), 1);
  > end

Or even more compactly, like

>>> A= [1 2 3 2 1; zeros(3, 5)]';
>>> I= [1 -1 -1; -1 1 -1; -1 -1 1];
>>> A= [A(:, 1) I(A(:, 1), :)]
A =
   1   1  -1  -1
   2  -1   1  -1
   3  -1  -1   1
   2  -1   1  -1
   1   1  -1  -1

Which indeed suggest, that many Matlab operations, apparently needing the repmat, can actually be handled with some 'clever' indexing scheme.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜