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 日

0 投票

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 件のコメント

Joel Olenga
Joel Olenga 2022 年 7 月 5 日
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.
Joel Olenga
Joel Olenga 2022 年 7 月 5 日
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?
Joel Olenga
Joel Olenga 2022 年 7 月 5 日
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!
Stephen23
Stephen23 2022 年 7 月 5 日
e = [3,-9];
s = join(string(e),',')
s = "3,-9"
Joel Olenga
Joel Olenga 2022 年 7 月 6 日
Even better! thank you Stephen23!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Import from MATLAB についてさらに検索

質問済み:

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