How to use a For loop to plot sine waves?

25 ビュー (過去 30 日間)
Mustafa Ali
Mustafa Ali 2021 年 3 月 10 日
コメント済み: Walter Roberson 2023 年 10 月 19 日
I need to use a for loop to plot one cycle of sine waves on the same figure and their frequencies vary from 50Hz to 250Hz with the increment of 10Hz. This is my code at the moment:
  1 件のコメント
Mathieu NOE
Mathieu NOE 2021 年 3 月 10 日
hello
I don't understand the relationship between this code and a sine wave
Z looks to me like the expression of an electric impedance - BTW the capacitor term should be written 1/(2*pi*f*C)

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

回答 (2 件)

Frances McBride
Frances McBride 2021 年 3 月 10 日
Since you did not include any errors that you are getting, I will come up with solutions based on some possible errors that you may be encountering.
  1. Plotting multiple plots on the same figure
Consider using "hold." Adding the following to your function will allow you to plot multiple plots on the same figure that you defined prior to creating your forloop. https://www.mathworks.com/help/matlab/ref/hold.html
hold on
figure
for i=1:10
f=50:i:250
Z=sqrt(R.^2+(1/2*pi*f*C).^2);
plot(Z,f)
end
Additionally, consider adding parentheses to the 1/2 term. You may be telling matlab to put pi in the denominator of 1/2, so be careful there.
  1. The outputted plot is not a sine wave
To create a sine function, use the built-in MATLAB function sin(). This automatically calculates the sine function using radians. To use degrees, use sind(). The plot you have here is a square root curve, not a sine wave.
  1. Unrecognized function or variable 'R'; unrecognized function or variable 'C'
You will get this error if you have not defined the constants in your equation for Z. If you have previously defined these constants in your script/function then you will likely not get this error. I brought this up because you didn't include where you defined R and C.

Prajwal Sangalad
Prajwal Sangalad 2023 年 10 月 19 日
hold on
figure
for i=1:10
f=50:i:250
Z=sqrt(R.^2+(1/2*pi*f*C).^2);
plot(Z,f)
end
  3 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 10 月 19 日
Walter, @Prajwal Sangalad has just copied the code from the answer posted above by @Frances McBride.
Walter Roberson
Walter Roberson 2023 年 10 月 19 日
Even if that were true, @Dyuman Joshi, @Prajwal Sangalad has posted an Answer to the question, and is morally responsible for dealing with responses to their Answer.

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

カテゴリ

Help Center および File ExchangeGraphics Performance についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by