0

How can i convert a numeric array to a single string, where array numbers will be separated with a comma ?

(e.g. convert A=[1 2 3] to a string '1,2,3')

Moreover, is there any way to apply the same above in case that matrix A contains variables in a for loop?

(e.g.

for i=1,10 A(i)=[1 1 i+1]; end

As variable i varies, I need to obtain a string '1,1,i+1'

thanks a lot !

4 Answers 4

1

There is a num2str() function

>> test =[123 124 125] % 3 element vector
test =

   123   124   125

>> num2str(test) % 1 element string
ans =

123  124  125

and also a function to write ASCII delimited files

the process can easily be reversed with the str2num function, as dan pointed out

Sign up to request clarification or add additional context in comments.

2 Comments

how can i get back the numeric array ?
@user3270686 just use str2num
0

I think you need this:

for i=1:10 
    disp(['1,1,',num2str(i+1)])
end

Note: Try to avoid 'i' as the iteration variable.

The output:

1,1,2
1,1,3
1,1,4
1,1,5
1,1,6
1,1,7
1,1,8
1,1,9
1,1,10
1,1,11

Comments

0
for i=1:10 
    s = sprintf('%d,', A);
    S{i} = s(1:end-1);
end

Comments

0

The function mat2str does just that:

>> A = [1 2 3];
>> mat2str(A)
ans =
[1 2 3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.