How do I create a script for a summation then plot?

I'm trying to convert this function to script:
then once it's in script plot it.
I wrote the script:
n=[1:10];
x=0:0.1:2*pi;
sys=(n/(n.^3)+4)*(sin(n*x))
and got back:
error: Test: operator *: nonconformant arguments (op1 is 1x10, op2 is 1x63)
error: called from
Test at line 3 column 4
error: evaluating argument list element number 1
error: called from
Test at line 3 column 4
How can I get an output?
Thank you so much!

 採用された回答

Star Strider
Star Strider 2016 年 10 月 2 日

1 投票

You’re close. You have to use the meshgrid or ndgrid functions to create matrices to allow you to vectorise the calculation. (The alternative is to use two meshed for loops. Using the matrices produced by ndgrid is easier and more efficient.) You also need to vectorise every multiply and divide operation in your ‘sys’ assignment (as well as the exponentiation, that you coded correctly), that I converted to an anonymous function here for my convenience. The ‘N’ and ‘X’ matrices are both (10x63) so this creates a result matrix of the same dimensions. The sum function sums the columns by default.
With those tweaks, your code works:
n=[1:10];
x=0:0.1:2*pi;
[N,X] = ndgrid(n,x);
sys = @(n,x) (n./(n.^3)+4).*(sin(n.*x));
sys_sum = sum(sys(N,X));
The plot is straightforward. I leave it to you.

2 件のコメント

newbie
newbie 2016 年 10 月 2 日
Thank you so much!!
Star Strider
Star Strider 2016 年 10 月 2 日
My pleasure!
Thank you for the smiley! That’s a first for me here!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating, Deleting, and Querying Graphics Objects についてさらに検索

タグ

質問済み:

2016 年 10 月 1 日

コメント済み:

2016 年 10 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by