Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shortcut to execute the current line in Matlab code?

When you select a line / multiple lines of code in Matlab, you can press F9 to execute it / them.

Is there a shortcut to execute the current line of code? This would enable you to go down line per line with your arrow down key and execute the corresponding line with this shortcut.

like image 229
Karlo Avatar asked Mar 10 '16 12:03

Karlo


1 Answers

While this is an older question, I don't find the only answer particularly satisfying.

This works in MatLab R2020b and R2021a at least (not sure about others).

On the home tab select Favorites, then New Favorite, then a cleaned version of the following code from this answer (https://stackoverflow.com/a/36149189/9096420) can be entered into the Code: section

currentEditor = matlab.desktop.editor.getActive; 
originalSelection = currentEditor.Selection; assert(originalSelection(1)==originalSelection(3)); 
currentEditor.Selection = [originalSelection(1) 1 originalSelection(1) Inf]; disp(currentEditor.SelectedText); 
eval(currentEditor.SelectedText); 
currentEditor.Selection = originalSelection + [1 0 1 0];

After that select Add to quick access toolbar and you can run one line at a time with Alt+1 (It is actually Alt and then 1 very shortly after, as opposed to simultaneously)

Note: The last line of this code will drop the cursor one line in the Editor. If you want it to stay on that line, just remove this last part.


The one place where this does fail is when you run clear all, because this line is evaluated before (second to last line above) you go a line down (last line above). So the clear all will still work, but the cursor will not drop and you will get an error: Unrecognized function or variable 'originalSelection'.

like image 96
Dylan_Gomes Avatar answered Nov 12 '22 19:11

Dylan_Gomes