My code works as a script file but produces errors as a GUI function, how do I fix it?

조회 수: 5 (최근 30일)
I managed to get the code in the last thread I posted working, however, since it is a GUI project, I need to transfer it from the script file I worked it on, onto the main GUI file. Here is the code for the function file:
function rowcolPush_Callback(hObject, eventdata, handles)
str = get(handles.plainText, 'String');
key = get(handles.keyText, 'String');
numKey = double(upper(str2num(key)));
sortKey = sort(numKey);
numArray = double(upper(str));
spaceArray = numArray(~isspace(numArray));
lenStr = numel(spaceArray);
lenKey = length(key);
array = zeros(round(lenStr/lenKey),lenKey);
if rem(lenStr,lenKey) ~= 1
spaceArray(1,(numel(array)-lenStr)+lenStr) = double('X');
end
outputArray = reshape(spaceArray,lenKey,round(lenStr/lenKey))';
%------
x = find(numKey ~= sortKey);
x2 = x([2,1]);
if isempty(x) == 0
outputArray(:,x) = outputArray(:,x2);
end
outputNum = reshape(outputArray(:,1:end), [1 20]);
outputStr = char(outputNum);
set(handles.cipherText,'String',outputStr);
guidata(hObject, handles);
I start getting errors at the %---- mark. x2 returns an error while indexing, saying that the index exceeds matrix dimensions. If I try to comment that part out and skip to outputNum, it gives an error with reshape, saying that the number of elements must not change in order to reshape.
When I run this code (defining str as 'TO SERVE AND TO PROTECT' and key as 'ALERT') as a script file without any functions, it works fine and produces the output I want. However, running this code in the GUI doesn't work. Is there something I'm forgetting/missing?
For reference, I am using the same string and key in the GUI and script file.

채택된 답변

per isakson
per isakson 2018년 12월 1일
편집: per isakson 2018년 12월 1일
One observation
sortKey = sort(numKey);
...
x = find(numKey ~= sortKey);
x2 = x([2,1]);
x will be empty if numkey is already sorted.
Set a breakpoint an check the size of x.
And
numKey = double(upper(str2num(key)))
str2num is not intended for letters; it returns empty for letters
See
  댓글 수: 1
Samir Saidi
Samir Saidi 2018년 12월 1일
It turns out my error was with str2num, removing it made x and x2 work, while I had made another mistake in changing numArray and spaceArray (spaceArray was defined first in the script file, and numArray was defined next) so I returned those to the same values the script file had and now my program works. I also didn't know about the debugging feature; that's how I caught the mismatch in array values. Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by