Question

I tried to find an answer to this question in the advanced search but couldn't find one. I might have missed it, in which case, apologies.

I guess it is a simple question, but i'm having trouble fixing it. I have a cell array, with each cell containing an array of doubles. First of all I need to know which cell has the longest array length. Once this is known, the other cells' arrays elements need to be replicated to match the length of the longest one.

That is, for example:

resp = {[1 3 2 6 4] [4 2 5]}

I don't know a priori whether resp{1} or resp{2} is larger.

The output I would like to have is a new cell array resp_new = {[1 3 2 6 4] [4 2 5 4 5]}. That is, to add in resp{2} its own elements (possibly randomly) to match the length of resp{1}.

So far, what I have can be summarized as follows:

Responses = {[1 3 2 6 4] [4 2 5]};

% I could have something like this for finding the longest array of doubles in my cell array:
val=cellfun(@(x) numel(x),Responses);
longest=Responses(val==max(val));

% or something like this, returning only the lengths.
tmp = cellfun(@length,Responses);

The problem I have, I don't know very much how to proceed in replicating its own elements in the shortest array to match the length of the second one.

Any help would be greatly appreciated! thank you and best regards.

Marc

Was it helpful?

Solution

That should do it:

Responses = {[1 3 2 6 4] [4 2 5]}

sizeLongest = max(cellfun(@numel, Responses));
Responses = cellfun(@(x) [x x(randi(numel(x), 1, sizeLongest - numel(x)))], Responses, 'UniformOutput', false);

First, it takes the size of the longest sequence. Then, it uses cellfun and, for each array x, it concatenates itself with N random elements from itself, where N = sizeLongest - numel(x).

Results:

>> Responses{:}
ans =

     1     3     2     6     4


ans =

     4     2     5     5     2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top