nashynash
nashynash

Reputation: 375

Accessing data from cell arrays at the same time

If A is a (x,y) cell array having n cells and each of them is a vector of size (m,n) and of type double.

Example: If A is a 1x2 cell array
A = 
[100x1 double]  [100x1 double]

Suppose I want to access the first element of each cells at the same time, how can we do so?

Similarly, if we need to access the ith element from every cell, how do we generalise the code?

Upvotes: 2

Views: 166

Answers (3)

Novice_Developer
Novice_Developer

Reputation: 1492

An alternative way would be to simply access the cell elements directly , for example we have a cell like you defined

A{1}(1:10) = randi([2 5],1,10);
A{2}(1:10) = randi([2 5],1,10);

now if you want to access the ith elements simply declare i and they will be retrieved in the matrix below

 i = 3;

ObsMatrix = [A{1}(i) A{2}(i)]

ObsMatrix =

     2     5

If A has unknown number of cell you can simply use a for loop , It will pick ith element from every cell index and put it in ObsMat

i = 3;
for j=1:numel(A)
ObsMat(end + 1) = A{j}(3);
end

cellfun is also a wrapper function for for loop

ObsMat =

     2     5

Upvotes: 1

User1551892
User1551892

Reputation: 3364

cell creation with two 1*10 arrays:

A {1} = zeros(1,10)  ;
A {2} = zeros (1,10) ;

A = [1x10 double] [1x10 double]

Adding some data which will be used for fetching later:

A {1}(5) = 5 ;
A {2}(5) = 10 ;

Routine to fetch the data at same index from both arrays inside cell:

cellfun (@(x) x(5),A)

ans = 5 10

Upvotes: 4

NLindros
NLindros

Reputation: 1693

As User1551892 suggested, you could use cellfun. Another way is to restruct the cell to a matrix first. The speed on the operation depends on the number of cells and the size of the matrix within each cell.

% Number of cells
x = 3;
y = 2;

% Size of matrix 
m = 1;
n = 100;

% Add some random numbers 
A = cell(x,y);
for i = 1:numel(A)
    A{i} = round(rand(m,n)*100);
end

% Index to pick in each matrix
idx = 5;

% Convert to matrix
B = [A{:}];

% Pick the number
val = B(idx:(n*m):end);

Doing som tic-toc measurements, the method above is faster for the example values. As long as the one of n or m is small the method is ok. But if both m and n grows large, cellfun is better (faster)

val = cellfun(@(x) x(idx), A);

Upvotes: 2

Related Questions