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

5 vues (au cours des 30 derniers jours)
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.

Réponse acceptée

per isakson
per isakson le 1 Déc 2018
Modifié(e) : per isakson le 1 Déc 2018
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 commentaire
Samir Saidi
Samir Saidi le 1 Déc 2018
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!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Entering Commands dans Help Center et File Exchange

Produits


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by