Matthias Pospiech
Matthias Pospiech

Reputation: 3494

Convert Matlab array into cell array

I fail to convert a matlab array into a array of cell values.

stacksize = size(resultStack.('f'),1); % 2897 values
exportc = cell(stacksize+1, 4);

exportc{1,1} = 'top';
exportc{1,2} = 'bottom';
exportc{1,3} = 'left';
exportc{1,4} = 'right';

exportc{2:end,:} = mat2cell(resultStack.('f'), 1:stacksize, 1:4);

This ends with the error

Input arguments, D1 through D2, must sum to each dimension of the input matrix size, [2897 4].

What am I doing wrong?

Upvotes: 1

Views: 628

Answers (2)

Colin T Bowers
Colin T Bowers

Reputation: 18530

UPDATE: Rody has spotted a second problem in your code beyond the one I mention here. You should incorporate his fully corrected solution into your code, and if you are happy with it, mark his response as the answer. Don't mark this response as the answer as it is incomplete.

Use parentheses () when allocating a cell array to a subset of another cell array, eg

%# A simple example
A = cell(2, 2);
B = {'hello', 'world'};
A(1, :) = B;

In your code, you need to change your last line to:

exportc(2:end,:) = mat2cell(resultStack.('f'), 1:stacksize, 1:4);

Note that curly braces {} are reserved for indexing into the contents of a single cell of a cell array.

Upvotes: 0

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

You're not using mat2cell correctly. Here's how to use it:

C = mat2cell(resultStack.('f'), ones(stacksize,1), ones(1,4)) 

this means: you specify that each row of the output cell C should contain the next 1 row and 1 column of resultStack.f (which is the reason behind all those 1's).

Also, as indicated by Colin T. Bowers, you should use barece-indexing (()) to copy stuff from another cell, and only use bracket-indexing ({}) when retreiving data from a cell.

Therefore, the complete, corrected version of your code should be:

stacksize = size(resultStack.('f'),1); % 2897 values
exportc = cell(stacksize+1, 4);

exportc(1,:) = {'top' 'bottom' 'left' 'right'};
exportc(2:end,:) = mat2cell(resultStack.('f'), ones(stacksize,1), ones(1,4));

Alternatively, since your desired output permits it, you can use the newer, better, simpler, num2cell command:

exportc(1,:)     = {'top' 'bottom' 'left' 'right'};
exportc(2:end,:) = num2cell(resultStack.('f'));

Upvotes: 3

Related Questions