How to access double arrays in a cell array?

20 ビュー (過去 30 日間)
MiauMiau
MiauMiau 2016 年 6 月 11 日
コメント済み: Stephen23 2016 年 6 月 12 日
Hi everyone,
I have a 1x5 cell array, where each of these 5 columns contains a 20x1 double array.
Now I have the following two questions:
  1. How can I for instance access from this cell array, the first two rows of all the double array it contains (such that I would ideally end up with a 2x5 array of doubles)?
  2. Is there any easy way to construct from this cell array a 20x5 array of doubles, where all rows but the i-th are set to zero?
Many many thanks

採用された回答

Stephen23
Stephen23 2016 年 6 月 11 日
編集済み: Stephen23 2016 年 6 月 11 日
Here are two solutions to your two tasks. First create some fake data:
>> fun = @()randi(9,20,1);
>> C = {fun(),fun(),fun(),fun(),fun()};
1. first two rows of each numeric array:
>> N = 2; % pick the number of rows
>> cell2mat(cellfun(@(c)c(1:N,:),C,'Uni',0))
ans =
8 6 4 7 4
9 1 4 3 8
2. All rows except the Nth are zero:
>> tmp = cell2mat(C);
>> R = 4; % pick the row
>> tmp(R~=(1:size(tmp,1)),:) = 0
tmp =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
9 9 8 7 5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
  2 件のコメント
MiauMiau
MiauMiau 2016 年 6 月 11 日
many many thanks, your answers were really helpful. In the case of 2., is it possible to do the same thing (setting everything except a particular row to zero), while keeping the original format (the 1x5 cell)?
Stephen23
Stephen23 2016 年 6 月 12 日
@MiauMiau: yes, you should use a for-loop and cell indexing.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by