How to return boolean in if else statement and the return value will link to anothe if else statement in Matlab? - 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?

Related

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.

if/else statement not executing 'if' statement

I have been trying to print some complex numbers. If the complex number (modTrace) is like 'a-ib' then my code:
modTrace
v = [real(modTrace(:)) imag(modTrace(:))].';
fprintf(fileID,'%e+%ei\n',v);
gives the output as:
2.355387e-13+-7.217925e-13i
To avoid the extra + sign in front of the negative imaginary piece I write:
v = [real(modTrace(:)) imag(modTrace(:))].';
if imag(modTrace(:))>0
fprintf(fileID,'%e+%ei\n',v);
else
fprintf(fileID,'%e%ei\n',v);
end
Now in the output the 'if' is not being executed. So if I have a complex number 'a+ib' it prints
'a bi' and if a complex number is 'a-ib' it prints 'a-bi' according to the else statement.
if I then modify the code like:
v = [real(modTrace(:)) imag(modTrace(:))].';
if imag(modTrace(:))<0
fprintf(fileID,'%e%ei\n',v);
else
fprintf(fileID,'%e+%ei\n',v);
end
then again the 'if' statement in not being executed. So for a complex number 'a-ib' the output is 'a+-bi' and the 'else' statement in being executed correctly.
Could any body please help me to find the output in the correct form?
Thanks.
I think that in this case you are better off using a loop:
for k = 1:length(modTrace)
if imag(modTrace(k))>0
fprintf(fileID,'%e+%ei\n',real(modTrace(k)), imag(modTrace(k)));
else
fprintf(fileID,'%e%ei\n',real(modTrace(k)), imag(modTrace(k)));
end
end
You can't vectorize it that easily because if you pass a vector to if it only evaluates true when (http://www.mathworks.com/help/matlab/ref/if.html):
the result is nonempty and contains all nonzero elements (logical or
real numeric). Otherwise, the expression is false.

Combine isfield and ~isempty within the same test

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')

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

use debugger in matlab

i want to debug following simplest code in matlab and clarify why it executes always if statement
function testfile(x)
if 3<x<6
disp('in the middle of range');
else
disp('out of range');
end
end
i have used following code for debugger
echo testfile on
testfile(-2)
in the middle of range
testfile(6)
in the middle of range
why it does not execute else statement?i have used following code as a test
5<4<8
ans =
1
so does it mean that writing if statement in this style is wrong?a i understood it is same as if 5<4 || 4<8?then it makes clear for me why it executes only if statement and never reaches to else
5<4<8 is evaluated as (5<4)<8. If we resolve the expression in the parentheses first, we have 0<8, which is true. Test with 5<4==0, which evaluates to true.
What you want to do is check whether x is both bigger than 3 and smaller than 6, i.e.
3<x && x<6