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

回答(2 个)

Walter Roberson
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
The end operator must be used within an array index expression.
This error occurs because end was used to index an array that does not exist yet.
  3 个评论
Stephen23
Stephen23 2025-7-4,5:52
H20Vs might be a table, in which case that syntax does not generate a comma-separated list.

请先登录,再进行评论。


Raag
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
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 = 2×2 cell array
{[ 1 2]} {[3 4]} {[5 6 7]} {[ 8]}
abc{1:end,1}
ans = 1×2
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ans = 1×3
5 6 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Walter Roberson
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by