2010-08-20 23 views
5

MATLAB有幾個選擇敏感的功能。例如,如果您選擇一些文本並按F9鍵,它會評估您的選擇。 (除非您重新映射了鍵盤設置。)如何檢索MATLAB中的選定文本?

我希望能夠通過快捷方式複製此功能。因此,例如,我想單擊顯示當前選擇的快捷方式。我的快捷回調將是disp(GetSelection())

但是進入GetSelection

回答

5

感謝@Yair Altmanundocumented Matlab,我能夠弄清楚java命令,使其工作。

把這個快捷方式(或功能通過快捷鍵調用):

%# find the text area in the command window 
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance; 
try 
    cmdWin = jDesktop.getClient('Command Window'); 
    jTextArea = cmdWin.getComponent(0).getViewport.getComponent(0); 
catch 
    commandwindow; 
    jTextArea = jDesktop.getMainFrame.getFocusOwner; 
end 

%# read the current selection 
jTxt = jTextArea.getSelectedText; 

%# turn into Matlab text 
currentSelection = jTxt.toCharArray'; %' 

%# display 
disp(currentSelection) 
+0

這很酷。謝謝。 – 2010-08-23 10:31:14

0

我不相信有任何方法可以控制或閱讀Matlab文本編輯器中的選擇,但Mathworks網站上沒有提到這樣的API(至少從Google上快速搜索)。如果您希望此功能啓用更高級的文本編輯功能,那麼您可能需要考慮將.m文件編輯器設置爲外部編輯器(http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/brxijcd.html)。從自定義GUI中的UIcontrol中讀取選擇可能是可能的,但我不認爲這是你想要的。

0

如果你想使用這樣的,但高亮顯示文本編輯器中,而不是在命令窗口。

爲了能夠快速檢查變量的nnz(),儘管可以將嵌套try-catch中的代碼更改爲任何需要的值,我使用下面的代碼。

最後,我在Matlab的右上角用這段代碼創建了一個快捷方式,通過按Alt-1可以快速訪問它。

try 
    activeEditor = matlab.desktop.editor.getActive; 
    currentSelection = activeEditor.SelectedText; 

    try 
     eval(sprintf('val = nnz(%s);',currentSelection)) 
     disp(sprintf('>> nnz(%s) = %s',currentSelection,num2str(val))) 
    catch ex 
     disp(ex.message) 
    end 
catch ex 
    disp(ex.message) 
end 
相關問題