How to separate characters in a cell array by commas

Hello I have the following code:
e = [3 0 -6];
n = length(e);
e_str = cell(1,n);
for i = 1:n
e_str(1,i) = {num2str(e(i))};
end
disp(e_str)
{'3'} {'0'} {'-6'}
I'd like to separete the output with commas as follows:
{'3'} {','} {'0'} {','} {'-6'}

 Accepted Answer

Wondering why you want that. But it can be done as follows:
e = [3 0 -6];
n = length(e);
e_str = cell(1,2*n-1);
for i = 1:n
e_str(1, 2*i-1) = {num2str(e(i))};
if i<n
e_str(1, 2*i) ={','};
end
end
disp(e_str)
{'3'} {','} {'0'} {','} {'-6'}

6 Comments

Thank you so much Chunru! I wanted to export {'3'} {'-9'} to a .csv file. However the .csv interprete 3 -9 as a date. Separating the values with commas is an alternative solution.
I'd like all the values, e.g., 3, -9 to be in the same cell.
"However the .csv interprete 3 -9 as a date. "
No it does not.
A CSV file is a simple text file, it cannot "interpret" anything: exactly the text that you write into a text file will be the text that exists in that text file. Nothing is "interpreted" by the fact of it being a CSV file.
However if you make the mistake to open a CSV file using MS Excel, then it is quite likely that MS Excel will mess up your data. MS Excel does that all the time:
However that is MS Excel that is causing the problem, not the CSV file format (which exists independently of MS).
"I'd like all the values, e.g., 3, -9 to be in the same cell."
Then why does your question clearly show them in separate cells?
Thanks for pointing out the Excel issue. That's why I added commas in between the values so Excel does not interprete them as date.
"Then why does your question clearly show them in separate cells?"
Sorry for the confusion. That was just a follow-up question for which I've found the answer as follows:
clc
e = [3 -9];
n = length(e);
e_str = cell(1,2*n-1);
for i = 1:n
e_str(1, 2*i-1) = {num2str(e(i))};
if i<n
e_str(1, 2*i) ={','};
end
end
Beams_el = {horzcat(e_str{1,:})}
Beams_el = 1×1 cell array
{'3,-9'}
Thanks again for your help!
Even better! thank you Stephen23!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!