ntough
ntough

Reputation: 363

How to convert a vector to a cell array in matlab?

I have two pieces of codes as the following:

nodes = randsample ( n_nodes, round(j*n_nodes) )-1;      
nodes_seqs = arrayfun (@transfer, nodes, 'UniformOutput', false );

nodes = num2str(nodes);

nodes = cellstr(nodes);
file_n = strcat('fasta','_','myfilename' );  % file  name

fastawrite(strcat( file_n, '.fas' ), nodes, nodes_seqs);

The other one is:

nodes = 0 : n_nodes-1;

nodes_seqs = arrayfun (@transfer, nodes, 'UniformOutput', false );

nodes = num2str(nodes);

nodes = cellstr(nodes);
file_n = strcat('myfilename' );  % file  name

fastawrite(strcat( file_n, '.fas' ), nodes, nodes_seqs);

The first one runs as expected. However, I got an error for the second one. After checking the variables, I got that in the second one, the nodes is a 1 by 1 cell array. I was confused. How comes it works on the first one, not the second one? Many thanks for your time and attention.

Upvotes: 1

Views: 63

Answers (2)

ntough
ntough

Reputation: 363

I figured it out. The main reason here is: in the first piece, the randsample returns a column vector, while in the second piece, the nodes is initialized to be a row vector. After adding a transpose, it works.

Upvotes: 0

bern
bern

Reputation: 366

In the second case since nodes is a cell array you need to use

nodes = cell2mat(nodes) instead of num2str as your data is of type cell at that point not num.

Here is a link to the function documentation on Mathworks

Other options are the functions cell2struct() or cell2table()

Upvotes: 1

Related Questions