Reputation: 433
I am trying to write the output from a variable length cell array to a single column cell array.
Eg:
I have
A a;b
B c
C b;c
D a;b;d
E e;g;h
F a;b
as the input file. I want to read all the entries in the second column into separate cells in a row and store the output as the following:
a
b
c
b
c
a
b
d.... and so on.
I tried
for m=1:size(txt)
c(:,m)=strsplit(txt{m},';');
end
However, I am unable to write the output into a column and getting the following error:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
I understand that the dimensions of c
should be more than that of size(txt)
but I am not sure how to enter write the output from c
into the first empty cell present in the column.
Upvotes: 0
Views: 83
Reputation: 104464
This is because you have declared c
to be a matrix but you want it to be a single column. In addition, strsplit
creates a cell array of results here each split string is placed in an element in the cell array. Also, this cell array is a row-wise cell array, meaning that you will get a cell array of dimensions 1 x N
where N
is the total number of strings resulting from the call the strsplit
.
As such, what I would recommend you do is create a master cell array to store all of the strings as you iterate through each row, then concatenate and create one final cell array at the end.
Assuming the code you wrote up until this point is correct, do something like this:
c = cell(numel(txt), 1);
for m = 1 : numel(txt)
c{m} = strsplit(txt{m}, ';');
end
c = horzcat(c{:});
The first line creates a master cell array to store our string split characters per line of the text file. Next, for each line of the file, we split the string with the semicolon character as the delimiter and we place these split results into the right cell in the master array. Once this is finished, we use horzcat
to place all of the characters into a single row of cells in the end. This creates a row of cell array elements though. Using horzcat
is required as we are concatenating many row-wise cell arrays together into a single row. Trying to do this vertically will give you an error. Simply transpose the result if you want a column:
c = horzcat(c{:}).';
Upvotes: 2