MATLAB Answers

0

Unable to use a value of type cell as an index

Asked by Daniel Schmeer on 1 Nov 2019
Latest activity Edited by Adam
on 1 Nov 2019
I can't work out why my implementation of title works in one function and not in the second one when they are functionally exactly the same. Why would this error appear for the second function while function one executes perfectly.
Ive also run each part of the line in the command window seperately and everything works okay.
function one(dataset, time)
figure('Name', dataset.name);
for i = 1:16
if i == 9
figure('Name', dataset.name + " 2");
end
if i < 9
subplot(8,1,i);
plot(x, y);
title(dataset.subtitle(i)); <------------------
xlabel(x_axis);
elseif i >= 9
subplot(8,1,i - 8);
plot(x, y);
title(dataset.subtitle(i)); <-------------------
xlabel(x_axis);
end
end
end
function two(dataset, title, x, y, x_axis)
figure('Name', title);
for i = 1:16
if i == 9
figure('Name', title + " 2");
end
if i < 9
subplot(8,1,i);
plot(x, abs(y(i,:)));
title(dataset.subtitle(i));
xlabel(x_axis);
elseif i >= 9
subplot(8,1,i - 8);
plot(x, abs(y(i,:)));
title(dataset.subtitle(i));
xlabel(x_axis);
end
end
end

  1 Comment

Can you share your input entries for your functions?

Sign in to comment.

Products


Release

R2019b

1 Answer

Answer by Adam
on 1 Nov 2019
Edited by Adam
on 1 Nov 2019
 Accepted Answer

You are passing in a variable called title to the second function. This will hide the function of the same name so that this instruction:
title(dataset.subtitle(i));
is no longer calling the title function, but is instead trying to index into your variable called title using dataset.subtitle(i) as an index.
Rename your variable to something else and it should be fine.
Always try to remember never to use function names as variable names!!
See this thread if you want to read more on this

  2 Comments

Thank you. Stupid error on my part
It's extremely easy to do! I've been working in Matlab for almost 14 years and I still do it plenty of times. After a while you get used to decoding the error message though and immediately start looking for that.
In this case, for the line on which you had the error there was only one thing actually being used as an index and clearly i was not a cell array.
So the only other logical reason for that particular error was that it was trying to index into a variable called title rather than call a function. Once you deduce that you instantly see the title variable being passed in.
So long as you remember that type of logical reasoning you can usually find the inevitable cases where you do this very quickly.

Sign in to comment.