Ignoring Octave-specific code in Matlab 2024b

1 次查看(过去 30 天)
I have a following bit of code specific to Octave, in a project that is also meant to be run in Matlab:
if (isOctave())
% Set the tick label precision
set(gca, 'xticklabel', cellstr(num2str(get(gca, 'xtick') (:), "%.2f"))) %#ok<SBTMP,*ALL>
set(gca, 'yticklabel', cellstr(num2str(get(gca, 'ytick') (:), "%.2f"))) %#ok<SBTMP,*ALL>
% Set axis font size
set(gca, 'fontsize', 12)
end
That particular code is needed for Octave to display figures properly.
And isOctave.m is as follows:
function retval = isOctave
persistent cacheval; % speeds up repeated calls
if isempty (cacheval)
cacheval = (exist ("OCTAVE_VERSION", "builtin") > 0);
end
retval = cacheval;
end
isOctave() has been tested to properly return 0 (false) in Matlab and 1 (true) in Octave.
Now, in Matlab an error message is produced due to the indexing with a colon:
Error: File: foobar.m Line: 117 Column: 41
Invalid array indexing.
And since the code to be executed is guarded with isOctave(), which returns 'false', logically that code section should not even be executed in Matlab. So it's weird that such error is being generated. And it even persist after adding the suppresstion %#ok<SBTMP,*ALL> in there.

回答(1 个)

Steven Lord
Steven Lord 2025-4-11
That error occurs before the code is executed, when MATLAB parses it. That is not syntactically valid MATLAB code and MATLAB can tell "just by looking at it", without trying to run it, that it is not valid.
In this case, wrap your call to get in calls to reshape instead of trying to chain indexing and it works in MATLAB.
set(gca, 'xticklabel', cellstr(num2str(reshape(get(gca, 'xtick'), [], 1), "%.2f")))
  1 个评论
Lassi
Lassi 2025-4-11
编辑:Lassi 2025-4-11
Indeed, that preprocessing has been the problem, not the actual code execution. I forgot to mention that the issue can simply be fixed by removing the colon indexing (:).
EDIT: ok, got the reshaping to work. It was an artifact of syntax checking passing in Matlab, but code not getting execured. But during Octave exectuion I was still missing the second parameter '1' for reshape().

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

产品


版本

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by