How to convert a cell column of numerical data in a cell array to a matrix or column vector containing those numerical data?
26 views (last 30 days)
Show older comments
Hello,
I'm dealing with a cell array as shown below,
A = {[1205:1:1211], [7]; [1881], [1]; [2449:1:2458], [10]};
and would like to convert the first column of cells into a column vector. In other words, I would like to have a column vector B that outputs the following.
B = [[1205:1:1211]'; [1881]'; [2449:1:2458]']
I tried using cell2mat but it does not work because it has something to do with the second column in A. I do not want to have to delete the second column of A either. How can I do this in a simple and easy to understand way? I would prefer having a solution that would work for however many cells of data that are in that first column in A.
I am using 2015a btw. Any help would be appreciated. Thanks.
0 Comments
Accepted Answer
Azzi Abdelmalek
on 11 Aug 2015
Edited: Azzi Abdelmalek
on 11 Aug 2015
A = {[1205:1:1211], [7]; [1881], [1]; [2449:1:2458], [10]};
B=cellfun(@(x) x',A,'un',0)
5 Comments
Stephen23
on 12 Aug 2015
Edited: Stephen23
on 12 Aug 2015
"Not exactly sure what the difference is."
- {} braces refer to the data inside the cells.
- () parentheses refer to the cells themselves.
This is clearly explained in the documentation:
Also note that this is consistent with all MATLAB indexing: parentheses always return arrays of the same class as the variable they are indexing into: numeric arrays return numeric data, character arrays return character data, structures return structures, cell arrays return cell arrays. Only in the case that you wish to delve into the cells do you need to use braces.
Your code cell2mat(A{:,1}) extracts the data from inside the cell array A into a comma separated list using this: A{:,1}. If the data inside are not cell arrays then you have just provided cell2mat with a list of non cell variables, thus the error. If you want to pass the cells themselves to cell2mat, then refer to them using parentheses: cell2mat(A(:,1)).
In the case that the cell array A contains another cell array, then cell2mat(A{:,1}) would not be an error, as the curly brackets extract this second cell array and it then gets passed to cell2mat.
More Answers (1)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!