Assigning array values to cell array based on condition
8 次查看(过去 30 天)
显示 更早的评论
I have two equally-sized vectors of indices like the following:
A = [1, 1, 1, 2, 2, 3, 3, 3, 3];
B = [6, 3, 7, 4, 7, 13, 16, 4, 1];
I want to assign the values of B into cell arrays based on the value of A at the same index, i.e.:
C{1} = B(A==1);
C{2} = B(A==2);
C{3} = B(A==3);
In reality, A contains all integers from 1 to 1600 (monotonically increasing, but each integer appears a different number of times), so it is impractical to write all lines out. So far, I have solved this with a loop (in each iteration, I create the mask C = B(A==iteration)), but loops are inefficient, so are there better ways to do it?
Similarly, I want to use this to assign values to the elements of a vector v. For example:
v(1) = sum(M(C{1}));
v(2) = sum(M(C{2}));
Where M is some other large vector from which we select the relevant entries by the indices in C as indicated. Again, this is currently implemented as a loop (i.e. v(i) = sum(M(B(A==i))) ), which works, but again, are there better ways to do it?
0 个评论
采纳的回答
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!