Combine isfield and ~isempty within the same test - matlab

I have written a lot of Matlab code using structs and I have the following problem recurring.
I often need to test if a field exists and is not empty. So far, my solution is:
if isfield(var, 'field')
if ~isempty(var.field)
...
when one or the other test fails I need to perform the very same action. In these cases the solution is far from being elegant. For example:
if isfield(var, 'field')
if ~isempty(var.field)
fieldOk = true;
else
fieldOk = false;
end
else
fieldOk = false;
end
A better solution would be to do both tests at once. I could write a function that wraps all this but I am wondering if there is a native Matlab solution.

What about:
if isfield(var, 'field') && ~isempty(var.field)
fieldOk = true;
else
fieldOk = false;
end
The logical operator X && Y just evaluates Y if X is true.
Have a look here. Therefore it's exactly what you need. But you may have to turn it around:
if ~isempty(var.field) && isfield(var, 'field')

Related

CPLEX C++ constant constraint

I am making a CPLEX model with C++, and I need a function like:
IloConstraint f(...){
IloConstraint constr;
if(condition1){
constr = (x+y >= 1);
return constr;
}
if(condition2){
constr = false;
return constr;
}
constr = true;
return constr;
}
I think that I succeded in creating a true and false constraints by
constr = (x==x); and
constr = IloNot(x==x);
I assume that this approach is not very optimal because it adds extra conditions and variables. Is there a more optimal and more readable way to do this? Something like
constr = IloConstraint(IloFalse); ?
IloConstraint(IloFalse) will not work since this will be interpreted as IloConstraint((IloConstraintI*)0) (IloFalse just expands to the literal 0 (zero)), which will create a constraint without implementation.
There is no literal for a true or false constraint. You can go without extra variables if you do something like IloExpr(env, 1) == IloExpr(env, 1) (and != for the false constraint). Another option for a constant true constraint would be use an empty IloAnd or an empty IloOr.
However, just going with x == x, 1 >= 2 or things similar to that seems a lot more readable to me. Additional expressions should usually not pose a problem. The engine will remove those in preprocessing.
Another option would be to use IloCplex::ifThen() to create a conditional constraint. Maybe this is even more readable then your function that returns a constraint.

How to return boolean in if else statement and the return value will link to anothe if else statement in Matlab?

I have the following if else statement that created by myself in order to link to the if else statement given in second part:
m=4
if m==3
disp(true)
else
disp(false)
Second part ( this code is fix cannot be change):
if (true)
A=Hello World
else
A=Bye
If using the first part code, my output will be
A=Hello World
but my desire output is
A=Bye
Anyone one have idea to edit the first part, because now my return value in first part not able to link to my second part.
If you can't change the second part's code, I'm afraid your desire cannot be fulfilled. Or rather, I'm afraid your code won't run at all, because your perenthesis, quotes, end-statement (and arguably semicolons) are not in place.
if true
A = 'Hello World';
else
A = 'Bye';
end
This code will return A = 'Hello World', no matter what, since true is always true. If-else conditions work like this:
if (*what's in here evealuates to true*)
%do stuff
else (*if what's up there does not evaluate to true*)
%do other stuff
Clearly, true will always evaluate to true. So the above if-else condition will always return A = 'Hello World'.
You don't need two if statements in order to accomplish this task. One is more than enough to perform all what you need:
m = 4;
if (m == 3)
A = 'Hello World';
else
A = 'Bye';
end
disp(A);
A few comments concerning your code:
if statements need to be closed with an end
if (true) will always pass into the statement
the disp function doesn't assign a value, its only goal is to display it in the Command Window
in order to work with text, you have to enclose it within single quotes ' (char array) or double quotes " (string), more info here
If you posted only small excerpts of your code and you need to perform those two checks sequentially, in different parts of your script, then:
m = 4;
if (m == 3)
m_equals_3 = true;
disp('M == 3');
else
m_equals_3 = false;
disp('M ~= 3');
end
% then, somewhere else...
if (m_equals_3)
A = 'Hello World';
else
A = 'Bye';
end
% ...
I guess this is a homework exercise. You should disclose that if it’s the case.
The exercise requieres you to change the workspace such that the second bit of code evaluated the else case. This can be accomplished by changing the meaning of true. In your first bit of code, make it so that
true = flase;
Or equivalently,
true = 0;
Note that this is really bad form, if you ever do something like this outside of a homework exercise that explicitly asks you to do so, you’ll get fired or maybe even shot. You’ve been warned!
By the way, I assume that the missing quote characters around the strings and the missing ends are typos?

If and elseif, only the first line work?

L=1; Nx=51; PeriodicFlag=1; T=15; Nt=51;
spacedef='Pade6FirstDeriv'; casedef='LinearAdvection';
if (spacedef == 'Pade6FirstDeriv')
D1 = sparse(Pade6(Nx,dx,PeriodicFlag));
elseif (spacedef == 'Upwind3FirstDeriv')
D1 = sparse(Upwind3(Nx,dx,PeriodicFlag));
elseif (spacedef == 'Central4FirstDeriv')
D1 = sparse(Central4(Nx,dx,PeriodicFlag));
elseif (spacedef == 'Central2FirstDeriv')
D1 = sparse(Central2(Nx,dx,PeriodicFlag));
else
error(sprintf('Unknown spacedef = %s',spacedef));
end
In the above code, the if section is a small segment from a function I've constructed. I'm trying to get the function to know which methods to use based on my input (spacedef). Central2, Central4, Upwind3, and Pade6 are other functions I've written. The weird thing is that when spacedef =/= to 'Pade6FirstDeriv', I would get an error stating Error using ==, Matrix dimensions must agree. I've tried swapping the order of the if loop (by placing Central4, Central2, Pade6, and Upwind3 in the first line of the loop), and it seems like only the top line of the loop will work (the elseifs are not working). I'd greatly appreciate it if anybody can help me out. Thanks!
As has been noted in the comments, this is a common error when people first start comparing strings in MATLAB, and strcmp or strcmpi is generally the solution.
However, one solution the questions links in the comments don't present, and a solution I think looks much nicer, is the switch statement:
switch (spacedef)
case('Pade6FirstDeriv')
D1 = sparse(Pade6(Nx,dx,PeriodicFlag));
case('Upwind3FirstDeriv')
D1 = sparse(Upwind3(Nx,dx,PeriodicFlag));
case('Central4FirstDeriv')
D1 = sparse(Central4(Nx,dx,PeriodicFlag));
case('Central2FirstDeriv')
D1 = sparse(Central2(Nx,dx,PeriodicFlag));
otherwise
error(sprintf('Unknown spacedef = %s',spacedef));
end
Note: if I expect others to use my code with string comparisons, I usually lower the input such that the comparison is case-insensitive, although I have not done that here.

Matlab function switching return/no return

In Matlab, I've got a function that is called after some special points are found on an image. Depending on how the nearby pixels of that "special point" are, the function must return a structure with many parameters or return nothing.
Is it possible to have a function that by deafult will return something but, in some cases, nothing should be returned? How that "return nothing"'s code should be like? Thank you.
One common trick in matlab is to use the empty matrix [] to indicate nothing. You could write your function something like (untested code):
function result = analyze(image, special_point)
% your code here
if pixels_are_ok
result.a = 1;
result.b = 2;
else
result = [];
end
If you call this function from your other code, you can use isempty to see if you got a result or not:
result = analyze(image, special_point)
if isempty(result)
display('did not find anything')
else
display('found some interesting results')
display(result)
end

MATLAB: Inverting a boolean value quickly

Is there a quicker way than the following to 'flip' a true or false to its opposite state?
if x == true
x = false;
else
x = true;
end
Yes, perhaps only five lines of code is nothing to worry about but something that looks more like this would be fantastic:
x = flip(x);
You could do the following:
x = ~x;
u can use negation statement.
I cant remember how it works in matlab, but i think is something like
x = ~x;
Franck's answer is better (using ~), but I just wanted to point out that the conditional in yours is slightly redundant. It's easy to forget that, since you already have a boolean value, you don't need to perform a comparison in your conditional. So you could have just done this...
if x
x = false;
else
x = true;
end