vector Entry lookup in matlab
Given a vector U n x 1 which contains the entries from 0,1,2,3 , I would like to create another vector V in char type such that the entry
0 in U will be '0' in V开发者_如何学编程 1 in U will be '1' in V 2 in U will be '12' in V 3 in U will be '123' in VWhat is the optimal way to do in matlab rather scanning each individual entry in the vector and then uses switch case?
You can easily define a set of rules and index into it.
rules={'0','1','12','123'};
out=rules(A+1)
In the above, A
is the vector you have.
Create an anonymous function to convert one element to the desired output and then use ARRAYFUN to apply this function to all of the inputs:
>> 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'
I think the simplest approach is to create a cell array 'C' containing your 4 string values, then index the array with 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'
And if you want V
to be a single character string instead of a cell array of strings, you can do this instead:
>> V = [C{U+1}]
V =
01121231210
I'd say create a hashmap with the set of pairs you gave there. Every time you want to insert into V based on U, insert the value paired with the key that is the value of the entry of U into V. I.e. if U[0] = 2, then do V[0] = myMap.get(2), or whatever the MATLAB syntax is.
Here's a vectorized version which is idiomatic Matlab:
Nevertheless, this in effect does a linear scan 4 times. If you truly want more efficiency, write a C mex function.
V = cell(size(U));
V{U==0} = '0';
V{U==1} = '1';
V{U==2} = '12';
V{U==3} = '123';
Edit:
gnovice's solution is far superior. See above.
精彩评论