Matlab: Search Columns and Add Values

时光毁灭记忆、已成空白 提交于 2020-05-31 05:48:44

问题


I am rather new to coding in general and I'm working on making a heat map, which is straightforward enough. But I am stuck in processing a piece of data.

I have an array 5x3 like below for example:

[9,9,1; 1,2,6; 3,6,2; 3,2,6; 5,6,2]

I want to scan through columns 2 and 3 and sum up column 1 when for each column 2&3 pair. In this case would result in 9 for 9,1 pair, 4 for 2,6 pair and 8 for 6,2 pair.

This is a simplified version, my columns 2,3 will have values from 1:20 Thanks for your help


回答1:


use accumarray to accumulate the first column base on the 2/3 column as index.

see test code

len=10;
maxidx=20;
data=[randi(100,len,1), randi(maxidx,len,1), randi(maxidx,len,1)];
output=accumarray(data(:,2:3),data(:,1), [maxidx, maxidx]);


来源:https://stackoverflow.com/questions/61289331/matlab-search-columns-and-add-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!