Unable to use a value of type cell as an index

145 次查看(过去 30 天)
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

采纳的回答

Adam
Adam 2019-11-1
编辑:Adam 2019-11-1
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 个评论
Adam
Adam 2019-11-1
编辑:Adam 2019-11-1
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Title 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by