user1008293
user1008293

Reputation: 11

matlab saving a cellarray

I have a script which does not fully work:

inputfield=input('Which field would you like to see: ','s')

if isfield(package, inputfield)

 fprintf('The value of the %s field is: %c\n',inputfield,...
 eval(['package.' inputfield]))

else fprintf('Error: %s is not valid field\n', inputfield)

end

First I define a structure in matlab and then i use the script on the structure:

package=struct('item_no',123,'cost',19.99,'price',39.95,'code','g')

package =

item_no: 123
   cost: 19.9900
  price: 39.9500
   code: 'g'

structurevalue Which field would you like to see: cost

inputfield =

cost

The value of the cost field is: 1.999000e+001

structurevalue Which field would you like to see: item_no

inputfield =

item_no

The value of the item_no field is: {

why cant it read value for item_no?

Upvotes: 1

Views: 138

Answers (1)

Sam Roberts
Sam Roberts

Reputation: 24127

Try:

fprintf('The value of the %s field is: %s\n',inputfield,...
    num2str(package.(inputfield)))

There were two issues with your version.

  1. You were passing both numbers and strings into the %c field in your fprintf string. When a decimal goes in, it is interpreted as a number and displayed in full precision, which is why 19.99 got displayed as 1.999000e+001. But when an integer goes in, it gets interpreted as a character, which is why 123 got displayed as '{' (ASCII character 123). Use num2str to convert numbers to strings for display. Also, use %s for a string of any length, rather than %c for a character.
  2. In general, it's not a good idea to use eval unless you have to. In this case, it's more convenient to use inputfield as a dynamic field name of package.

Upvotes: 1

Related Questions