Unable to use a value of type cell as an index

193 Ansichten (letzte 30 Tage)
Daniel Schmeer
Daniel Schmeer am 1 Nov. 2019
Bearbeitet: Adam am 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

Akzeptierte Antwort

Adam
Adam am 1 Nov. 2019
Bearbeitet: Adam am 1 Nov. 2019
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 Kommentare
Daniel Schmeer
Daniel Schmeer am 1 Nov. 2019
Thank you. Stupid error on my part
Adam
Adam am 1 Nov. 2019
Bearbeitet: Adam am 1 Nov. 2019
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Just for fun finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by