Using cellfun to extract specific rows from a cell array?

Hello,
I have a 1x6 cell array, 'Peaks':
Peaks = {199x4500} {192x4500} {167x4500} {171x1950} {157x1500} {191x1500}
I would like to create a new cell array, 'New_Peaks' using only 16 rows from each cell. The row numbers I want to choose are are in a 16X6 double array, 'Indices'.
Indices =
2 1 1 1 4 1
16 23 7 72 133 24
44 30 19 15 13 63
41 15 28 9 18 58
35 26 31 3 15 4
8 49 39 19 53 32
11 72 40 96 29 64
14 39 55 73 111 84
153 33 57 129 12 71
70 116 63 92 75 60
144 104 95 94 68 83
137 137 97 108 77 74
91 155 107 140 120 97
36 40 119 49 144 56
80 64 127 105 43 59
160 94 145 66 149 49
I tried the following line:
New_peaks = cellfun(@(x) x(Indices), all_peaks, 'UniformOutput', false)
But the output is a 1x6 cell array consisting of 16x6 doubles.
The output I want is:
New_peaks = {16x4500} {16x4500} {16x4500} {16x1950} {16x1500} {16x1500}
Is cellfun able to extract the contents of a cell array in this way?

3 件のコメント

the cyclist
the cyclist 2021 年 12 月 22 日
Can you upload the data, using the paperclip icon in the INSERT section of the toolbar? That makes it easier to see if code we try gives what you want.
omidm
omidm 2021 年 12 月 22 日
Hi, sure, uploaded the 'peaks' and 'indices' variables.
the cyclist
the cyclist 2021 年 12 月 23 日
Separate piece of advice: Don't name a variable "peaks", which shadows the name of a function. That can cause issues and confusion.

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

 採用された回答

Matt J
Matt J 2021 年 12 月 22 日
編集済み: Matt J 2021 年 12 月 23 日

0 投票

New_peaks =cellfun(@(a,b) a(b,:), Peaks,num2cell(Indices,1) ,'uni',0);

6 件のコメント

omidm
omidm 2021 年 12 月 22 日
Thanks! This worked.
omidm
omidm 2022 年 3 月 31 日
Hi Matt,
Do you have any advice on how I would write this line if my indices were stored in another cell array rather than a double array?
Matt J
Matt J 2022 年 3 月 31 日
Indices=num2cell(cell2mat(Indices),1)
New_peaks =cellfun(@(a,b) a(b,:), Peaks,Indices ,'uni',0);
omidm
omidm 2022 年 4 月 1 日
Thanks Matt. Unfortunately, my indices are in a 1X6 cell aray because each column has different dimensions.
[848 X 1] [901 X 1] [870X 1] [295 X 1] [46X 1] [163 X 1]
Therefore, cell2mat won't let me concatenate into a double matrix.
I guess my overall goal is to use one 1X6 cell array (Indices) to index another 1X6 cell array (Peaks).
Matt J
Matt J 2022 年 4 月 1 日
編集済み: Matt J 2022 年 4 月 1 日
In that case, you can just use Indices in its current form.
New_peaks =cellfun(@(a,b) a(b,:), Peaks,Indices ,'uni',0);
I would also encourage you to read the cellfun documentation to understand what this is doing.
omidm
omidm 2022 年 4 月 1 日
Great, thanks!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

質問済み:

2021 年 12 月 22 日

コメント済み:

2022 年 4 月 1 日

Community Treasure Hunt

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

Start Hunting!

Translated by