Hello guys,
i created a cell, with indices in the fields.
c=cell(2,2);
c{1,1}=[1,2,3];
c{2,1}=[7,8];
c{1,2}=[1,4];
c{2,2}=[3,5];
The goal is to extract and sum up values from another vector at this indices.
data=(1:10)';
The result should be a matrix (2x2, same size like c) with the results in it.
Pseudocode:
results(1,1)=sum(cell{1,1})=1+2+3
results(2,1)=sum(cell{2,1})=7+8
... and so on...
But this should be done automatically without a loop over the fields of the cell.

 採用された回答

madhan ravi
madhan ravi 2020 年 7 月 21 日

0 投票

cellfun(@sum,c)

4 件のコメント

Marc Gebhardt
Marc Gebhardt 2020 年 7 月 21 日
Well, this works, if data is 1,2,3,.. but not for random numbers or other values in data
Marc Gebhardt
Marc Gebhardt 2020 年 7 月 21 日
May this works...
cellfun(@(x) sum(data(x)),c,'UniformOutput',false)
madhan ravi
madhan ravi 2020 年 7 月 21 日
Mine works if the cell contains 1d vector, if otherwise you need to set the uniformoutput to false.
Bruno Luong
Bruno Luong 2020 年 7 月 21 日
Well your pseudo-code does not depend on DATA, and it's confusing to select DATA example that has value==indice.
cellfun(@(i) sum(data(i)), c)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Resizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by