2017-04-20 92 views
0

enter image description here爲什麼空字符串測試失敗?

function browsePushButton_Callback(hObject, eventdata, handles) 
% hObject handle to browsePushButton (see GCBO) 
% eventdata reserved - to be defined in a future version of MATLAB 
% handles structure with handles and user data (see GUIDATA) 
% show open file dialog 
[filename, pathname] = uigetfile({ '*.jpg'; '*.png';'*.bmp';'*.jpeg'; }, ... 
           'Open image', ... 
           '' ... 
           ); 
% obtain image-file's path 
imagePath = strcat(pathname, filename); 

% if the imagePath is not empty... 
if (imagePath ~= '')  
    image = imread(imagePath); 
    % digging out image related info 
    [pathstr,name,ext] = fileparts(filename) ; 
    fileinfo = imfinfo(imagePath); 
    FileSize1 = fileinfo.FileSize(1,1); 
    width = fileinfo.Width; 
    height = fileinfo.Height; 
    % 
    axes(handles.imagesPictureBox); 
    imshow(image); 
else 
    % if the imagePath is empty, display a error message 
    h = msgbox('Invalid Value', 'Error','error'); 
end 

錯誤消息

Error using ~= 
Matrix dimensions must agree. 
Error in OpenFileDialogBoxTest>browsePushButton_Callback (line 91) 
if (imagePath ~= '') 
Error in gui_mainfcn (line 95) 
     feval(varargin{:}); 
Error in OpenFileDialogBoxTest (line 42) 
    gui_mainfcn(gui_State, varargin{:}); 
Error in @(hObject,eventdata)OpenFileDialogBoxTest('browsePushButton_Callback', 
      hObject,eventdata,guidata(hObject)) 
Error while evaluating UIControl Callback 

回答

2

你應該使用strcmp比較字符串

if ~strcmp(imagePath,'') 
    ... 
end 

您使用預計這兩個字符數組是的不等於運營商一樣尺寸。

編輯:兩件事 1)當你使用uigetfile文件和路徑信息,請記住,輸出可以是數字。當用戶取消對話時就是這種情況。你應該抓住這種可能性。 2.)你從uigetfile的輸出構造絕對路徑的方式是錯誤的。有一個文件分隔符,即缺少'/'或'\'。我建議使用imagePath = fullfile(pathname, filename);而不是

2

首先,這不是檢查字符串是否爲空的正確方法。 ~= operator被設計用於在等長度的數組上工作元素(這些字符串通常不是)。字符串比較通常應使用strcmp。但是,要檢查一個字符串是否爲空,則應該使用isempty

...但所有這一切都是一個有爭議的問題,因爲不管怎樣,你都不應該檢查uigetfile的輸出。當用戶取消文件選擇,uigetfile輸出都設置爲0,所以你if說法應該是這樣的:

if isequal(filename, 0) 
    % if the imagePath is empty, display a error message 
    h = msgbox('Invalid Value', 'Error','error'); 
else 
    % obtain image-file's path 
    imagePath = fullfile(pathname, filename); % NOTICE I MOVED THIS INSIDE THE IF STATEMENT! 
    ... 
    % All the other stuff you want to do 
    ... 
end