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

 채택된 답변

Adam
Adam 2017년 5월 31일
편집: Adam 2017년 5월 31일
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.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

질문:

2017년 5월 31일

댓글:

2017년 5월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by