You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用拟合参数在MATLAB中绘制平滑余弦曲线?

Plotting a Smooth Cosine Curve with Fitted Parameters

Got it, let's break down how to generate that smooth cosine curve using the parameters you got from nlinfit. Here's a step-by-step guide with practical code examples:

Step 1: Generate Dense X Values

Your original x data is likely a set of discrete points— to get a truly smooth curve, you need more sampling points across the same interval. Use linspace to create a dense range of theta values:

theta_smooth = linspace(min(x), max(x), 1000); % 1000 points will give a nice, smooth curve

Step 2: Calculate Corresponding Y Values with Fitted Parameters

Use your predefined cos_fun and the fitted p parameters to compute the y-values for the dense theta points. The function already accounts for all three parameters automatically:

cos_fun = @(p, theta) p(1) + p(2) * cos(theta - p(3));
y_smooth = cos_fun(p, theta_smooth);

Quick recap of what each parameter does in the curve:

  • p(1): Y-offset (sets the baseline of your cosine wave)
  • p(2): Amplitude (controls the height of the wave peaks/troughs)
  • p(3): Phase (shifts the curve left or right along the x-axis)

Step 3: Plot the Curve (and Compare with Original Data)

To visualize how well your fit matches the original data, plot both the raw points and the smooth fitted curve together:

% Create a new figure window
figure;

% Plot original data points (using circles for clear visibility)
plot(x, y, 'o', 'DisplayName', 'Original Data');
hold on; % Keep the figure open to add the next plot

% Plot the smooth fitted curve (red solid line with thicker width for emphasis)
plot(theta_smooth, y_smooth, '-r', 'LineWidth', 2, 'DisplayName', 'Fitted Smooth Cosine Curve');

% Add labels, legend, and grid for readability
xlabel('Theta');
ylabel('Y Value');
title('Fitted Cosine Curve vs. Original Data');
legend;
grid on;

hold off; % Release the figure so you can create new plots later

Full Example Code

Putting everything together (assuming you already have your x, y, and fitted p parameters):

% Your existing fitting code (for reference)
cos_fun = @(p, theta) p(1) + p(2) * cos(theta - p(3));
p = nlinfit(x, y, cos_fun, [1 1 0]);

% Generate smooth curve data
theta_smooth = linspace(min(x), max(x), 1000);
y_smooth = cos_fun(p, theta_smooth);

% Plotting
figure;
plot(x, y, 'o', 'DisplayName', 'Original Data');
hold on;
plot(theta_smooth, y_smooth, '-r', 'LineWidth', 2, 'DisplayName', 'Fitted Curve');
xlabel('Theta');
ylabel('Y');
title('Smooth Fitted Cosine Wave');
legend;
grid on;
hold off;

That's all there is to it! The dense theta points ensure the curve looks smooth instead of a jagged line connecting your original data points.

内容的提问来源于stack exchange,提问作者guivann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 18:38:15