1

I am reading an input from a file and importing it into my data to run in Matlab:

    parts = strread(tline,'%s','delimiter',';')       
    employee(i).name = parts(1);
    employee(i).salary= str2double(parts(2));

Then I try to print it out:

for i = 1:3
 fprintf('salary: %.2f\n',employee(i).salary);
 fprintf('employee name: %s\n',employee(i).name);
end

The salary prints with no problem. But the for the variable "name" it gives an error:

Error using fprintf
Function is not defined for 'cell' inputs.
fprintf('employee name: %s\n',employee(i).name);

I looked for some other examples:

access struct data (matlab)

How do I access structure fields dynamically?

Matlab Error: Function is not defined for 'cell' inputs

How do i define a structure in Matlab

But there is nothing to address this case, where only string is not working.

I have not explicitly declared the data as struct, i.e. inside the code there is nowhere the "struct" word is included, but Matlab apparently automatically understand it as an "Array of structures".

Any hints what might be missing here?

All comments are highly appreciated!

Community
  • 1
  • 1
Gerry Woodberg
  • 336
  • 1
  • 11
  • 1
    Given the error message I would imagine `employee(i).name` is a `cell` and not a `char`. What does `class(employee(i).name)` return? – sco1 Jun 16 '16 at 20:18
  • 1
    I think `employee(i).name` is a cell. So see if you can do `str = employee(i).name{1}` and then use `str`. – Autonomous Jun 16 '16 at 20:18
  • it retuns: ans = cell – Gerry Woodberg Jun 16 '16 at 20:22
  • 1
    So...that means `parts` is probably a `cell` array and you'll want to [access data in a cell array](http://www.mathworks.com/help/matlab/matlab_prog/access-data-in-a-cell-array.html) when pulling data into `employee` – sco1 Jun 16 '16 at 20:27
  • @ParagS.Chandakkar - Thanks! It works. Anyway to avoid the need to use the str? – Gerry Woodberg Jun 16 '16 at 20:29

1 Answers1

3

The issue is that employee(k).name is a cell (check with iscell(employee(1).name)) and the format string %s doesn't know how to handle that.

The reason that it is a cell is because strread returns a cell array. To grab an element from the result (parts), you want to use {} indexing which returns a string rather than () which will return a cell.

employee(i).name = parts{1};
Suever
  • 64,497
  • 14
  • 82
  • 101