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'}

 채택된 답변

Chunru
Chunru 2022년 7월 5일
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

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.
Stephen23
Stephen23 2022년 7월 5일
편집: Stephen23 2022년 7월 5일
"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!
e = [3,-9];
s = join(string(e),',')
s = "3,-9"
Even better! thank you Stephen23!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

질문:

2022년 7월 5일

댓글:

2022년 7월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by