matrix dimension must agree - matlab

My dropdown list contains the ff. strings: Low Pass, High Pass, Band Pass, Stop Band. Whenever I choose the Low Pass, the error below shows. The code below works for the rest.
My goal is to make the edtCutoff2 and txtRange invisible when I choose Low Pass and High Pass but the code below works only for High Pass.
Error:
Error using ==
Matrix dimensions must agree.
Error in untitled>popFreqResp_Callback (line 168)
if ((str == 'Stop Band') | (str == 'Band Pass') == 1)
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in untitled (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in#(hObject,eventdata)untitled('popFreqResp_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
Code Snippet
function popFreqResp_Callback(hObject, eventdata, handles)
list=get(handles.popFreqResp,'String');
str=list{get(handles.popFreqResp,'Value')};
if ((str == 'Stop Band') | (str == 'Band Pass') == 1)
set(handles.edtCutoff2,'Visible','on');
set(handles.txtRange,'Visible','on');
else
set(handles.edtCutoff2,'Visible','off');
set(handles.txtRange,'Visible','off');
end

You shouldn't compare strings using '==', because it will throw the error you see if the strings are not the same length. Essentially '==' is comparing two matrices of type char - if they don't have the same length, '==' isn't defined. Since 'Low Pass' has a length of 8, and 'Band Pass' has a length of 9, you can't compare them in this manner.
Use strcmp instead. Or strcmpi if you don't care about case.

Related

How do I export result of visdiff of two models programmatically (Matlab versions <= R2016b)?

I am comparing two models using visdiff. I can see the results as a comparison tab. I see options on the GUI to export results in different format.
How do I export these results programmatically?
I am able to export it for non-model files.
But for model files it throws following error:
Subscript indices must either be real positive integers or logicals.
Error in linediff>tokenize (line 153)
cls = tok_class(double(s));
Error in linediff (line 18)
tok1 = tokenize(line1,ignore_whitespace);
Error in textdiff>i_CreateHTML/writeModifiedLine (line 158)
[newline1,newline2] = linediff(line1,line2,showchars,ignore_whitespace);
Error in textdiff>i_CreateHTML (line 464)
writeModifiedLine(line1,a1(n),line2,a2(n));
Error in textdiff (line 42)
htmlOut=i_CreateHTML(source1,text1,readable1, ...
Error in comparisons_private (line 9)
out = textdiff(varargin{:});
Error in visdiff (line 52)
htmlOut = comparisons_private('textdiff',filename1,filename2,showchars);

error Undefined function or method 'min' for input arguments of type 'struct'

I have matrix 3x108 which contains dimension data. I want to find min and max value of my matriks in each row. Here's my code:
P = load('grading/dimension.mat');
min_P = min(P,[],3);
max_P = max(P,[],3);
but it gives me error:
??? Error while evaluating uicontrol Callback
??? Undefined function or method 'min' for input arguments
of type 'struct'.
Error in ==> guikedelaizulfa>identifikasi_Callback at 1427
min_P = min(P,[],3);
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> guikedelaizulfa at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==>
#(hObject,eventdata)guikedelaizulfa('identifikasi_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
Can you help me? Thanks
Using P=load(...) the function returns a single struct which contains all variables. Assuming you have used the variable name X when saving, you can access the variable using P.X. I recommend to set a breakpoint and take a look at the loaded data using the Variable Explorer or the fieldnames function.

Matlab error- Cell contents reference from a non-cell array object

Why do I get the error Cell contents reference from a non-cell array object. Below is my code. Can anybody tell me what is wrong with this code?
%Read data from database.
curs = exec(conn, sprintf(['SELECT description.imageName'...
' , description.brand'...
' , description.price'...
' , description.size'...
' , description.clothingDescription'...
' FROM description WHERE description.imageID ="%s"'],imagename));
curs = fetch(curs);
close(curs);
%Assign data to output variable
results = curs.Data;
disp(results);
set(handles.edit1,'String',results{1});
set(handles.edit2,'String',results{2});
set(handles.edit3,'String',results{3});
set(handles.edit4,'String',results{4});
set(handles.edit5,'String',results{5});
This is the full error message
Cell contents reference from a non-cell array object.
Error in image_desc1>image_desc1_OpeningFcn (line 90)
set(handles.edit1,'String',results{1});
Error in gui_mainfcn (line 220)
feval(gui_State.gui_OpeningFcn, gui_hFigure, [], guidata(gui_hFigure), varargin{:});
Error in image_desc1 (line 42)
gui_mainfcn(gui_State, varargin{:});
This is one of the sample data execute in command window when typing the code in
WHERE description.imageID =1
'High Neck Tee' 'ZALORA' [40] 'S,M,L,XL' 'Blush High Neck by ZALORA'
After typing the whos, it show this sentence in command window
Name Size Bytes Class Attributes
results 1x1 8 double
The error communicates the message clearly as it is. The variable results is not a cell array and you are trying to extract non-existing results{1},...,results{5}. Hence the error.

How do I use MATLAB's inputParser with optional string inputs? The documentation says "use a validation function" but it's unclear how to do that

I have a MATLAB file that contains a single top-level function, called sandbox. That function in turn contains two nested functions, mysum and myprod, which are identical in functionality and what parameters they allow except that one uses #sum internally and the other uses #prod internally. My goal is to create a wrapper function to use in both mysum and myprod that takes care of all the validation and input parsing. This function is called applyFunc.
Here's where it gets tricky. mysum and myprod come in two forms:
mysum(v) returns sum(v, 1).
mysum(v, 'imag') returns sum(v, 1) + 1i
Any other combinations of input should throw an error.
I'm having trouble using inputParser to parse these various combinations of input, specifically the optional string input. Here's the code:
function sandbox()
%% Data
v = [1 4; 3 3];
%% Calculations
s = mysum(v);
si = mysum(v, 'imag');
p = myprod(v);
pi = myprod(v, 'imag');
%% Accuracy tests
assert(isequal(s, [4 7]))
assert(isequal(si, [4+1i 7+1i]))
assert(isequal(p, [3 12]))
assert(isequal(pi, [3+1i 12+1i]))
function x = mysum(varargin)
x = applyFunc(#sum, varargin{:});
end
function x = myprod(varargin)
x = applyFunc(#prod, varargin{:});
end
end
function x = applyFunc(func, varargin)
p = inputParser();
p.addRequired('func', #(x) validateattributes(x, {'function_handle'}, {'scalar'}));
p.addRequired('v', #(x) validateattributes(x, {'double'}, {}, 'applyFunc:msg', 'v'));
p.addOptional('imag', '', #(x) validatestring(x, {'imag', ''})); % THIS LINE IS THE PROBLEM
p.parse(func, varargin{:});
f = p.Results.func;
v = p.Results.v;
strflag = p.Results.imag;
x = f(v);
if ~isempty(strflag)
validatestring(strflag, {'imag'});
x = x + 1i;
end
end
The line that's causing the problem is this one (as marked in the code above):
p.addOptional('imag', '', #(x) validatestring(x, {'imag', ''}));
The documentation for inputParser says that:
For optional string inputs, specify a validation function. Without a validation function, the input parser interprets valid string inputs as invalid parameter names and throws an error.
Unfortunately I don't have any idea how to do this. Is there something simple Im missing or what? If the 'imag' argument isn't passed at all (as in the assignment of s and p), the code works fine, but if I do pass it, I get this error:
Error using sandbox>applyFunc (line 32)
The value of 'imag' is invalid. It must satisfy the function:
#(x)validatestring(x,{'imag',''}).
Error in sandbox/mysum (line 18)
x = applyFunc(#sum, varargin{:});
Error in sandbox (line 7)
si = mysum(v, 'imag');
Any help?
The problem is that validatestring returns the matching string from the cell argument ({'imag',''}) rather than a Boolean indicating if it passes validation. Instead, use strcmp and any:
#(x) any(strcmp(x,{'imag', ''}))
Also, with validatestring, if the input string did not match either 'imag' or '' (actually just 'imag' since empty strings only match in R2014a+), it would throw an error rather than returning false so that the inputParser could return the appropriate error.
Another nice way to fix the problem is to change the syntax of applyFunc entirely so that instead of just 'imag' as an optional string input argument, use a Parameter-Value with 'imag' as the parameter and a validated boolean as the input.
The input definition suggested by Amro in the comments:
p.addParameter('imag', false, #(x)validateattributes(x, {'logical'}, {'scalar'}))
The usage:
mysum(x,'imag',true)
mysum(x) % default is equivalent to mysum(x,'imag',false)
This would simplify the rest of the code with p.Result.imag being a logical scalar. I would suggest:
x = f(v) + p.Result.imag*1i;
The problem is not inputParser, I think the issue is with validatestring.
1) First it does not match on empty strings:
>> x = ''
x =
''
>> validatestring(x, {'imag',''})
Expected input to match one of these strings:
imag,
The input did not match any of the valid strings.
Caused by:
Error using validatestring>checkString (line 85)
Expected input to be a row vector.
2) Second, if it successfully matches, it returns the resolved string (from one of the valid choice), instead of true/false. inputParser requires that the validation function either return a boolean, or nothing but throws error on failure.

MATLAB error while convert str2num

i'm completely new to matlab and this is my first question.
I found a program like this
x = inputdlg('foo');
x = str2num(x{1})
and trying to make some gui from it, put this line to callback function of push button:
x=get(handles.edit1, 'String')
x=str2num(x{1})
and it works, but not after i add this the same thing with different variable
y=get(handles.edit2, 'String')
y=str2num(y{1})
command window said
Cell contents reference from a non-cell array object.
Error in regresilinear>pushbutton1_Callback (line 128)
x=str2num(x{1})
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in regresilinear (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in
#(hObject,eventdata)regresilinear('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
I found out that the output from command window is different when it's running and not with the same input.
When it got errors:
x =
0 1 2 3
when not (the first time)
x =
'0 1 2 3'
It doesn't give any error if i delete the str2num line.
I hope somebody can help fix the problem.
Start with a clear workspace and
x=get(handles.edit1, 'String');
x=str2num(x);
or better:
x=str2num(get(handles.edit1, 'String'));
{} are used for accessing the elements of a cell array. You are probably trying to use it on a string and that is why you are getting that error.