user3270686
user3270686

Reputation: 81

how to convert a number array to a single string in matlab

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 !

Upvotes: 0

Views: 172

Answers (4)

ben
ben

Reputation: 1390

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

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112769

The function mat2str does just that:

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

Upvotes: 0

Dan
Dan

Reputation: 45752

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

Upvotes: 0

Divakar
Divakar

Reputation: 221714

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

Upvotes: 0

Related Questions