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!

5
  • 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? Commented Jun 16, 2016 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. Commented Jun 16, 2016 at 20:18
  • it retuns: ans = cell Commented Jun 16, 2016 at 20:22
  • 1
    So...that means parts is probably a cell array and you'll want to access data in a cell array when pulling data into employee Commented Jun 16, 2016 at 20:27
  • @ParagS.Chandakkar - Thanks! It works. Anyway to avoid the need to use the str? Commented Jun 16, 2016 at 20:29

1 Answer 1

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};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the best answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.