MATLAB Answers

Can I plot a line function, and a plot function under an if statement?

2 views (last 30 days)
Farouk Omer
Farouk Omer on 4 May 2021
Edited: dpb on 5 May 2021
Hello, I'd like to know if it would be correct if I can put a line and plot function under an if statement. Can I do that? Or does it have to be after the end? It works when I try it but I but I'm trying to make sure that I arrange the code the correct way, since this is part of a maze project. I've highlighted the plot and line functions below.
% Current x and y positions:
% x = 3.5
% y = 3.5
h_r1 = 2; % Retrieves information of the location of the wall from the first row of the h variable.
h_c1 = 4; Retrieves information of the location of the wall from the fourth column of the h variable.
v_r1 = 1; % Retrieves information of the location of the wall from the 2 row of the v variable.
v_c1 = 4; % Retrieves information of the location of the wall from the fourth column of the v variable.
x12 = [ 3.5 2.5]; % Set x points for the path of the object.
y12 = [ 3.5 3.5]; % Set y points for the path of the object.
if v(v_r1,v_c1) == 0 % Condition for the situation where the vertical wall is equal to 0 (or is open).
disp('move left') % If the if condition is met,then highlighted statement is displayed.
line (x12,y12,'color','magenta') %Plots the next line path of the object using the x and y values, and is displayed in Magenta.
plot(x12,y12,'o') % Plots the next position of the object using the x and y values and creates a circular symbol ( )the symbol of the object) at that location.
elseif v(v_r1,v_c1) == 1 % Condition for the situation where the vertical wall is equal to 1 (or is closed).
disp('Move right') %, if the elseif condition is met then the highlighted text is displayed.
elseif h(h_r1,h_c1) == 0 % Condition for the situation where the horizontal wall is equal to 0 (or is open).
disp(' Move down ') % If the elseif condition above is met, then the highlighted text is displayed.
elseif h(h_r1,h_c1) == 1
disp('Move up')
end

Accepted Answer

dpb
dpb on 5 May 2021
Edited: dpb on 5 May 2021
"can put a line and plot function under an if statement. ...? It works when I try it ..."
It would seem you've answered your own question.
Whatever code that needs to be in whatever section of an if...[[elseif]..else]...end block is fine inside whichever clause it needs to be in to satisfy the logic needs of the program.
I can't think of anything other than not fully containing another block construct like a for...end block fully within a clause that couldn't be inside whatever part of the construct you wanted it.
If it were "after the end", then it would no longer be part of the conditional construct and thus be executed always; obviously not a satisfactory solution if it is only to draw the line sometimes and not other times.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by