error message 'The end operator must be used within an array index expression.'
14 次查看(过去 30 天)
显示 更早的评论
Hi,
When I try to plot
plot(H20Vs{1:end,1},H20Vs{1:end,2})
hold on
plot(M20Vs{1:end,1},M20Vs{1:end,2})
hold on
plot(N20Vlin{1:end,1},N20Vlin{1:end,2})
% hold on
% plot(P20Vs{1:end,1},P20Vs{1:end,2})
legend('a' ,'b', 'c', 'd', 'e', 'f', 'h', 'l', 'm', 'n')
I recieve this error message 'The end operator must be used within an array index expression.'
Does anyone have any idea why this could be happening? I noticed the last two plot functions don't cause this issue, only the first one.
Cheers
0 个评论
回答(2 个)
Walter Roberson
2025-7-4,3:59
It is likely that the error is in code before what was posted. For example,
a(end)=1
This error occurs because end was used to index an array that does not exist yet.
3 个评论
Stephen23
2025-7-4,5:52
H20Vs might be a table, in which case that syntax does not generate a comma-separated list.
Raag
2025-7-4,2:53
Hi Em,
The error you're encountering is due to how MATLAB interprets the end keyword when used inside cell array indexing with curly braces ({}). Specifically, the expression:
H20Vs{1:end,1}
is not valid because end is ambiguous in this context. MATLAB expects end to be used within a single array index expression, but here it's being used across two dimensions (1:end for rows and 1 for columns), which is not allowed with cell content indexing.
To fix this, you can extract the entire column of cells first using parentheses (), and then convert the cell array to a numeric array using cell2mat. Here's how we can do this:
% Corrected plotting code
plot(cell2mat(H20Vs(:,1)), cell2mat(H20Vs(:,2)))
hold on
plot(cell2mat(M20Vs(:,1)), cell2mat(M20Vs(:,2)))
hold on
plot(cell2mat(N20Vlin(:,1)), cell2mat(N20Vlin(:,2)))
legend('a', 'b', 'c', 'd', 'e', 'f', 'h', 'l', 'm', 'n')
This avoids the misuse of end and ensures the data is in the correct format for plotting.
The output on a mock data looks like:

For more details, refer:
2 个评论
Walter Roberson
2025-7-4,3:49
This analysis is incorrect. Using end with cell indexing is permitted.
abc = {[1 2], [3 4]; [5 6 7], [8]}
abc{1:end,1}
Walter Roberson
2025-7-4,9:03
@Stephen23 points out the possibility that the variables are a table. "end" indexing of a table is permitted.
H20Vs = table([1;5;7], [2;3;9]);
plot(H20Vs{1:end,1},H20Vs{1:end,2})
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!