Replace the value of one column conditional on another column

I have a problem to generate a vector with varying number of blocks. Suppose A=[0 1;0 1;0 2;0 2;0 2;0 3;0 3;0 3], the last column of A is the index for groups. I want to replace the value of the first column of A for different groups. For example, I want to replace the first few elements of A(:,1) with [0.5;0.8] if the second column equals 1. Replace the block elements of A(:,1) with [0.4, 0.6, 0.8] if the second column equals 2, etc., Is there any easy way to do that? Thanks

 Réponse acceptée

Adam
Adam le 31 Mai 2017
Modifié(e) : Adam le 31 Mai 2017
A( A(:,2) == 1, 1 ) = [0.5; 0.8];
A( A(:,2) == 2, 1 ) = [0.4; 0.6; 0.8];
works, but it is very brittle. It relies on there being exactly the number of elements in that 2nd column matching each criteria as you give it values in the array to assign. It is maybe ok for a small number of hard-coded cases, though still not ideal, but it doesn't scale well.
The fact that you have such specific length arrays to assign though implies that by some method or other you already know how many of each element there are ahead of the test given in the code below.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by