How to convert a vector to be a string

I'm trying to convert a vector to be a string. for example
[1,2,3,4] -> "[1,2,3,4]"
so I did write this func
function [output] = make_string(arr)
output ={};
for i=1:length(arr)
output{end+1} = strcat('[',num2str(arr{i}),']');
end
end
but unfortunately, it takes a lot of computing time and my script became really slow. So is there any other solution?
thanks a lot in advance

 Akzeptierte Antwort

Matt J
Matt J am 28 Mär. 2021

0 Stimmen

string(mat2str([1,2,3,4,5]))
ans = "[1 2 3 4 5]"

Weitere Antworten (1)

Ken Garrard
Ken Garrard am 28 Mär. 2021

1 Stimme

You don't need a cell array for this problem and your make_string function has errors. See doc 'cell arrays'.
If you want a comma between the values in the output string you can use the sprintf function.
s = ['[' sprintf('%g, ',A(1:end-1)) sprintf('%g]',A(end))];
This is also about 40% faster than mat2str.

4 Kommentare

Izzat Brgli
Izzat Brgli am 28 Mär. 2021
I'm doing this because I'm using the return from this function as row's name to index in a table.
Stephen23
Stephen23 am 28 Mär. 2021
"I'm using the return from this function as row's name to index in a table."
Converting to string is most likely an inefficient approach to "index in a table". If you show what you are doing then probably someone can show you a more efficient way.
Izzat Brgli
Izzat Brgli am 28 Mär. 2021
Bearbeitet: Izzat Brgli am 28 Mär. 2021
what do you recommend to do? because I agree with you it's inefficient
Stephen23
Stephen23 am 28 Mär. 2021
"what do you recommend to do?"
Exactly like I wrote in my last comment, I reccomend that you give more details of what you are currently doing, so that someone can help you. If you do not give example code, we cannot guess exactly what you are doing.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 28 Mär. 2021

Kommentiert:

am 30 Mär. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by