How to use object array elements with sprintf?

2 ビュー (過去 30 日間)
ScottPT303
ScottPT303 2015 年 6 月 18 日
コメント済み: ScottPT303 2015 年 6 月 18 日
Hi, I'm having trouble getting sprintf to allow a string from an object property as an acceptable input.
I have a defined class that has a property 'name'. In another function I've used a loop to define 3 objects of that class into an object array called 'objArray'. I'd like to use sprintf to write a text command but I'm getting an error. I eventually want to write multiple commands with a for loop iterating over the 3 objects in objArray, but I can't figure out the syntax yet for event just the first element of the objArray...
Code:
cmd = sprintf('Object_name: %s',objArray(1).name)
Error:
Error using sprintf Function is not defined for 'cell' inputs.
I've also tried with {}...
Code:
cmd = sprintf('Object_name: %s',objArray(1).name)
Error:
Cell contents reference from a non-cell array object
Am I missing something about the sprintf syntax or should I be using a different function?
Thanks

採用された回答

Guillaume
Guillaume 2015 年 6 月 18 日
It looks like the name property of your class does not contain a string but a cell array containing a string. You can check that with:
class(objArray(1).name)
I bet it says 'cell' instead of 'char', so either fix your property so it actually contains a string or simply extract the string from the cell with:
cmd = sprintf('Object_name: %s', objArray(1).name{1});
  1 件のコメント
ScottPT303
ScottPT303 2015 年 6 月 18 日
Thank you for the response! I did check the class. Since it is an object array then
class(objArray(1).name)
results in the name of the class (not the property 'name', unintended confusion). Your recommendation using thisObjArray(1).name{1} works! In this case I am actually calling the 'char' within the cell as you said. Thank you for the help!

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2015 年 6 月 18 日
t = objArray(1).name;
cmd = sprintf('Object_name: %s', t{1});

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by