Convert a value into a Matlab syntax string

1 回表示 (過去 30 日間)
Giovanni Camodeca
Giovanni Camodeca 2020 年 12 月 6 日
回答済み: Steven Lord 2020 年 12 月 6 日
Hi all,
is it possible to convert a value from an struct into a string using the Matlab syntax ?
e.g.
I folowing struct : exStruct.value = [1 0 0;0 1 0;0 0 1];
If i am using num2str(exStruct.value) the output is a char that looks like this:
val =
1 0 0
0 1 0
0 0 1
What i want is more sth. like this :
val =
[1 0 0;0 1 0;0 0 1]
Is this possible ?
Cheers

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 12 月 6 日
編集済み: Ameer Hamza 2020 年 12 月 6 日
You can do something like this
exStruct.value = [1 0 0;0 1 0;0 0 1];
out = ['[' strjoin(compose(repmat(' %d ',1,3), exStruct.value), ';') ']']
Result
>> out
out =
'[ 1 0 0 ; 0 1 0 ; 0 0 1 ]'

その他の回答 (2 件)

Rik
Rik 2020 年 12 月 6 日
You can do it like that, but it is already Matlab syntax if you add the square brackets, as arrays can be defined across multiple lines.
Anyway: you can split the resulting char into rows (e.g. with mat2cell), add semicolons between each (e.g. with sprintf('%s;', c{:}) removing the trailing semicolon), and add the brackets to either side.
If you have trouble implementing this, post a comment with the code you tried.

Steven Lord
Steven Lord 2020 年 12 月 6 日
mat2str([1 0 0;0 1 0;0 0 1])
ans = '[1 0 0;0 1 0;0 0 1]'
But if you're doing this so you can later on evaluate this text to define the variable, I would advise against it. The general consensus is to avoid eval wherever possible.

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by