hamideh
hamideh

Reputation: 225

size of inner elements of cells

I'm reading some data with their attribute (say A in which first row is ids and second row is their attribute value) . I'd like to place such data in a cell where the first column are the unique ids and second row their attribute. whenever there's duplicate values for the attribute, I'll put on the vacancy available on front of its row. for example I'd like to construct C

A =
 1     2     3     2
 2     4     5     9

C{1}=
1   2   0
2   4   9
3   5   0

when I'm going to test the size of inner homes in cell, e.g.

size(C{1},2)

ans = 3

size(C{1},1)

ans = 3

size(C{1}(1,:),2)

ans =  3

All return 3 since it occupies empty homes with 0. So how should I understand where to put my new data (e.g. (1,5))? Should I traverse or find the place of 0 and insert there? Thanks for any help.

Upvotes: 1

Views: 75

Answers (1)

Santhan Salai
Santhan Salai

Reputation: 3898

Why not use a cell-Array for these kind of problem? How did you generate your C matrix?

Even though you have used cell-Arrays for C matrix, each element of C is a matrix in your case, so that the dimensions should be constant.

I have used a cell array inside a matrix. (i.e) each elements takes its own size based on the duplicate sizes. for eg, you could see that C{2,2} has two values while C{1,2} and C{3,2} has only one values. you could easily check the size of them without checking for zeros. Note that, even if any values were zero, this code will still work.

The first column of the matrix represents identifiers while the second column represents the values which takes its own size based on the number of duplicates.

Here is my Implementation using accumarray and unique to generate C as a cell-array.

Code:

C = [num2cell(unique(A(1,:).')),  accumarray(A(1,:).',A(2,:).',[],@(x) {x.'})]

Your Sample Input:

A = [1     2     3     2;
     2     4     5     9];

Output:

>> C

C = 

[1]    [         2]
[2]    [1x2 double]
[3]    [         5]

>> size(C{2,2},2)

ans =

 2

>> size(C{1,2},2)

ans =

 1

From the DOC

Note: If the subscripts in subs are not sorted with respect to their linear indices, then accumarray might not always preserve the order of the data in val when it passes them to fun. In the unusual case that fun requires that its input values be in the same order as they appear in val, sort the indices in subs with respect to the linear indices of the output.


Another Example:
Input:

A = [1  2   1   2   3   1;
     2  4   5   9   4   8];

Output:

C = 

[1]    [1x3 double]
[2]    [1x2 double]
[3]    [         4]

Hope this helps!!

Upvotes: 1

Related Questions