Vector Typing Search in Matlab

For a vector U nx 1 that contains entries from 0,1,2,3 , I would like to create another vector V in char type such that writing 0 in U will be '0' in V
  1 in U will be "1" in V
  2 at U will be "12" at V
  3 at U will be "123" at V

What is the best way to do in MATLAB by scanning each individual record in a vector, and then using the switch case?

+3
source share
5 answers

You can easily define a set of rules and an index in it.

rules={'0','1','12','123'};
out=rules(A+1)

In the above example A, this is the vector you have.

+1
source

, ARRAYFUN, :

>> f = @(x) sprintf('%u', sum(10.^((x-1):-1:0) .* (1:x)));
>> x = 0:3

x =

     0     1     2     3

>> c = arrayfun(f, x, 'UniformOutput', 0)

c = 

    '0'    '1'    '12'    '123'
+1

, - C, 4 , U+1:

>> C = {'0' '1' '12' '123'};  %# Cell array with 4 strings corresponding to 0..3
>> U = [0 1 2 3 2 1 0];       %# Sample U vector
>> V = C(U+1)                 %# Index C with U+1

V = 

    '0'    '1'    '12'    '123'    '12'    '1'    '0'

, V , :

>> V = [C{U+1}]

V =

01121231210
+1

I would say create a hash map with the set of pairs that you gave there. Each time you want to insert into V based on U, insert the key-conjugated value, which is the value of writing U to VI; if U [0] = 2, then V [0] = myMap.get (2) or whatever MATLAB syntax.

0
source

Here is the vector version, which is the idiomatic Matlab:

However, it actually does a linear scan 4 times. If you really want to increase efficiency, write the C mex function.

V = cell(size(U));
V{U==0} = '0';
V{U==1} = '1';
V{U==2} = '12';
V{U==3} = '123';

Edit:

The gnovice solution is far superior. See above.

-1
source

All Articles