MATLAB Answers

Last else if graph not plotting

5 views (last 30 days)
if i==3600
hold on;
plot(x,C);
elseif i==10800
plot(x,C);
elseif i==36000
plot(x,C);
elseif i==36300
plot(x,C);
hold off;
end
In the above program, if i varies from 0 to 36300 or more then last plot is not happening and if I add one more else if i ==36600 then that will not get plot.

Accepted Answer

S. Walter
S. Walter on 2 Nov 2020
Edited: S. Walter on 2 Nov 2020
I tried the following:
% Clear the command window and close the figures
clc
close all
% Make a color vector for plots
col_vec = lines(4);
% Start a counter for the legend entry
cnt = 1;
% Loop over the entries
for i = 1 : 1 : 36300
% Make random data
x = 0:1:10;
C = rand(size(x));
% If/else statements - added some extra code for plotting clarity
if i==3600
hold on;
plot(x,C,'-o','MarkerFaceColor',col_vec(cnt,:))
leg{cnt} = 'first';
cnt = cnt+1;
elseif i==10800
plot(x,C,'-d','MarkerFaceColor',col_vec(cnt,:))
leg{cnt} = 'second';
cnt = cnt+1;
elseif i==36000
plot(x,C,'-s','MarkerFaceColor',col_vec(cnt,:))
leg{cnt} = 'third';
cnt = cnt+1;
elseif i==36300
plot(x,C,'-^','MarkerFaceColor',col_vec(cnt,:))
leg{cnt} = 'fourth';
hold off;
end
end
% Annotate the plot
legend(leg,'location','northeast')
axis([0 10 0 1.1])
grid on
xlabel('x')
ylabel('C')
When I do that, I get four lines with markers
However, as the other commenter said, placing hold on and hold off ahead of the if/else statements is more robust, because if the condition is not met, you might not get the right hold conditions.
  3 Comments
ANMOL BAKSHI
ANMOL BAKSHI on 3 Nov 2020
Yes, got it.
Really thanks for the suggestions and help.

Sign in to comment.

More Answers (1)

KSSV
KSSV on 2 Nov 2020
Try like this:
hold on
if i==3600
plot(x,C);
elseif i==10800
plot(x,C);
elseif i==36000
plot(x,C);
elseif i==36300
plot(x,C);
end
hold off
Though I don't understand..what is the purpose to plot like this.
  1 Comment
ANMOL BAKSHI
ANMOL BAKSHI on 2 Nov 2020
hold on
if i==3600
plot(x,C);
C3600 = C;
elseif i==10800
plot(x,C);
C10800 = C;
elseif i==36000
plot(x,C);
C36000 = C;
elseif i==36300
plot(x,C);
C36300 = C;
end
hold off
Tried that. Now, here C36300 is getting stored but plot for last else if is not happening.

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!