2
votes

Using MATLAB, I would like to create a new vector, in which the values in the original vector are replaced by corresponding numbers from another matrix.

Specifically, I have a large vector (30,000 x 1) in which the individual values in each cell correspond to locations in the brain (range: 0 - 166). These values are somewhat randomly spread across the vector (they correspond to brain locations). After running an experiment, I would now like to replace each instance of these values with a value that I've calculated experimentally. These values are stored in a corresponding matrix (167 x 2): the first column contains the value from the original matrix (0 - 166) and the second column contains the new value I'd like to replace the original value (0 - 6). So for example, if value 150 was associated with a score of 5 in my experiment, I'd like to replace each instance of 150 with a 5 in the original matrix.

original vector: [1; 1; 1; 1; 2; 2; 2; 2; 1; 1; 1; 1; 1; 1; 2; 2; 2; 2; ...]

identity matrix: [0 0; 1 4; 2 5; 3 2; ...]

new vector: [4; 4; 4; 4; 5; 5; 5; 5; 4; 4; 4; 4; 4; 4; 5; 5; 5; 5; ...]

Is there an easy way to solve this?

Thanks

4

4 Answers

5
votes
originalMatrix = [1; 1; 1; 1; 2; 2; 2; 2; 1; 1; 1; 1; 1; 1; 2; 2; 2; 2; 0; 3];
identityMatrix = [0 0; 1 4; 2 5; 3 2];
[~,ind] = ismember(originalMatrix,identityMatrix(:,1));
map = identityMatrix(:,2);
result = map(ind);

Edit

I keep getting this error: "Subscript indices must either be real positive integers or logicals."

It's because some values in originalMatrix don't have corresponding values in identityMatrix.

so you can ignore them by,

ind(ind==0) = [];
2
votes
indCol=identityMatrix(:,2);
newVector=indCol(originalVector+1)

Or, in one line:

newVector=identityMatrix(originalVector+168)
1
votes

I'm pretty sure there is a more efficient way, but this should get the job done. For every value in the range 0-166 i find the indexes of the original vector components which contains that value. This is stored in the vector called Indexes. Then I put the new value called identity_matrix(i,2) in new_vector at this Indexes.

new_vector = zeros(size(original_vector));
for i = 1:167
    Indexes = find(original_vector == identity_matrix(i,1));
    new_vector(Indexes) = identity_matrix(i,2);
end
0
votes

Here is a one-liner using bsxfun and multiplication (with the data from Kamtal's answer):

originalMatrix = [1; 1; 1; 1; 2; 2; 2; 2; 1; 1; 1; 1; 1; 1; 2; 2; 2; 2; 0; 3];
identityMatrix = [0 0; 1 4; 2 5; 3 2];
result = bsxfun(@eq,originalMatrix(:),identityMatrix(:,1)')*identityMatrix(:,2);