How to write the MATLAB code for generating such figure?

8 ビュー (過去 30 日間)
Assen Beshr
Assen Beshr 2022 年 2 月 13 日
回答済み: Riya 2024 年 2 月 5 日 6:26
  3 件のコメント
Atsushi Ueno
Atsushi Ueno 2022 年 2 月 13 日
x = 1:100;
y = rand(size(x)) * 300 + 9200;
y2 = y;
for i = 2:size(x,2)
y2(i) = min(y2(i-1),y(i));
end
scatter(x,y,'x');
xlabel('Run number');
ylabel('Total cost');
hold on
plot(x,y2);
hold off
legend('Solutions','Best solution');
ylim([9100 9700]);
Assen Beshr
Assen Beshr 2022 年 2 月 17 日
thank you Atsushi ueno ,you answer was exact what I want. thanks again lot.

サインインしてコメントする。

回答 (1 件)

Riya
Riya 2024 年 2 月 5 日 6:26
Hi Assen
Below is the MATLAB code for generating the figure as described. The code generates random y-values to simulate total cost, then finds the minimum cost up to the current point for each run number, and plots both the solutions and the best solution up to that point.
x = 1:100; % Run numbers
y = rand(size(x)) * 300 + 9200; % Simulate random total costs
y2 = y; % Initialize best solution array
% Loop through to find the best solution up to the current run
for i = 2:size(x,2)
y2(i) = min(y2(i-1),y(i));
end
% Scatter plot for solutions
scatter(x,y,'x');
xlabel('Run number'); % Label for x-axis
ylabel('Total cost'); % Label for y-axis
hold on % Hold on to add another plot to the figure
% Line plot for the best solution
plot(x,y2);
hold off % Release the hold to finish plotting
% Add legend
legend('Solutions','Best solution');
% Set y-axis limits
ylim([9100 9700]);
When you run this code in MATLAB, it will generate a scatter plot of the solutions and a line plot that tracks the best solution found up to each run number. The y-axis is limited to the range [9100, 9700] as specified.
For more information about ‘legend’ function refer the document below:

カテゴリ

Help Center および File Exchange2-D and 3-D Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by