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.
0 个评论
回答(1 个)
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")))
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Interactive Control and Callbacks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!