Reputation: 81
Is there any smart way to store elements of a matrix raw as a string array?
For example:
If A=[1 2 3; 4 5 6]
a 2x3 matrix, str(1)='1 2 3'
and str(2)='4 5 6'
; a 1x2 array
Upvotes: 0
Views: 56
Reputation: 2077
Unfortunately, I don't think there's a way to make it workout syntactically exactly like you requested. I see two options:
As Geoff mentioned str = cellstr(num2str(A))
will get the job done and you'll have to index it as str{1}
(note that str(1)
returns a cell array and not a string).
If you want an array, you can just use str = num2str(A)
eg
>> num2str(A)
ans =
1 2 3
4 5 6
>> str(1,:)
ans =
1 2 3
>> str(2,:)
ans =
4 5 6
Kept as a vector, you'll have to access your string with str(1,:)
.
Upvotes: 0
Reputation: 1603
There is a way (whether it is smart or not) to convert the matrix to a cell array of strings:
>> str = cellstr(num2str(A));
str =
'1 2 3'
'4 5 6'
Input matrix A
is converted to an 2x7 array of characters (two spaces between each number) via num2str
, and then we convert it to a cell array of strings via cellstr
. The first string is accessed by str{1}
and the second by str{2}
.
Upvotes: 4