フィルターのクリア

Best way to deal with index-data pairs with multiple data values per index

2 ビュー (過去 30 日間)
Andrew
Andrew 2015 年 6 月 22 日
回答済み: Walter Roberson 2015 年 6 月 22 日
Hello,
I have a large vector of index-data pairs that may contain multiple data values for any given index. The way this is represented in the data is that the index vector may contain repeated indices with the corresponding location in the data vector containing the multiple data values. For example
ind = [ 1, 2, 4, 2, 5, 6, 4, 4, 9];
data = [32, 14, 36, 45, 3, 1, 78, 90, 69];
In this case index 2 has data values of 14 and 45.
Now, what I want to do is to assign these data values into a matrix using the index values, and if multiple data values exist for a given index I want to take the maximum. For example, if ind contains indices for a 3x3 matrix I want the following (working off of the previous example)
mat = zeros(3);
mat = input_data(ind,data,mat)
OUTPUT:
mat = [32,90,0;
45, 3,0;
0, 1,69]
where, as you can see, the value for index 2 is 45 since 45 is greater than 36.
What is the best way to do this quickly? My vectors are very long so I don't want to use a loop because it will decrease performance too much. I suspect I will probably need to use the unique command (and possibly sort) somehow but I can't figure out how to implement it.
Any help is greatly appreciated.
Thanks,
Andrew

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2015 年 6 月 22 日
ind = [1,2,4,2,5,6,4,4,9];
data = [32,14,36,45,3,1,78,90,69]
out=reshape(accumarray(ind',data',[],@(x) max(x)),3,3)

その他の回答 (2 件)

Guillaume
Guillaume 2015 年 6 月 22 日
accumarray is perfect for this:
ind = [ 1, 2, 4, 2, 5, 6, 4, 4, 9];
data = [32, 14, 36, 45, 3, 1, 78, 90, 69];
m = accumarray(ind', data', [], @max)
You can reshape m afterward (or possibly pass the size to accumarray)

Walter Roberson
Walter Roberson 2015 年 6 月 22 日
mat = zeros(3);
maxdata = accumarray(ind(:), data(:), [numel(mat), 1], @max);
mat = reshape(maxdata, size(mat));

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by