Ignoring Octave-specific code in Matlab 2024b

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.

Antworten (1)

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 Kommentar

Lassi
Lassi am 11 Apr. 2025
Bearbeitet: Lassi am 11 Apr. 2025
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().

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Interactive Control and Callbacks finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2024b

Gefragt:

am 11 Apr. 2025

Bearbeitet:

am 11 Apr. 2025

Community Treasure Hunt

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

Start Hunting!

Translated by