Error while vectorizing my code

5 ビュー (過去 30 日間)
Mohsin Shaikh
Mohsin Shaikh 2020 年 12 月 27 日
コメント済み: Mohsin Shaikh 2020 年 12 月 28 日
x = 0:0.01:5; %% range of x values for graph
y = zeta_func(x);
plot(x,y),xlabel('x'), ylabel('zeta(x)'), title('Zeta(x) Graph'),
%% function definition
function zeta_val = zeta_func(x)
%% zeta(x) = summation of 1/x^n
%% here summing from n = 1 to 50
n = 1:1:50;
terms = 1./power(n,x); %% performing 1/x^i for all n
zeta_val = sum(terms); %% summing the values
end
I get the following error
Error using .^
Matrix dimensions must agree.
Error in zeta_gpu>zeta_func (line 11)
terms = 1./power(n,x); %% performing 1/x^i for all n
Error in zeta_gpu (line 2)
y = zeta_func(x);
Over here the function is being called on the whole array x. But I want to do element wise.
How do I acheive this over here?

採用された回答

Cris LaPierre
Cris LaPierre 2020 年 12 月 27 日
The error is because your vectors x and n are not the same length. x has 501 elements while n has 50. Also, power is doing n.^x. From how you worded things, perhaps you want x.^n?
Assuming you want every n to be raised to every x, I would look into using meshgrid. You can set it up so the rows represent unique values of x and the columns unique values of n (or vice versa). Then just sum by each x so you can create your plot.
x = 0:0.01:5; %% range of x values for graph
y = zeta_func(x);
plot(x,y),xlabel('x'), ylabel('zeta(x)'), title('Zeta(x) Graph'),
%% function definition
function zeta_val = zeta_func(x)
%% zeta(x) = summation of 1/x^n
%% here summing from n = 1 to 50
n = 1:1:50;
% create meshgrid, with unique x in each column, unique n in each row (50x501)
[X,N]=meshgrid(x,n);
terms = 1./power(N,X); %% performing 1/x^i for all n
zeta_val = sum(terms); %% summing the values
end
  3 件のコメント
madhan ravi
madhan ravi 2020 年 12 月 27 日
Ah didn't see your comment Jan :), have to increase my font size ;)
Mohsin Shaikh
Mohsin Shaikh 2020 年 12 月 28 日
Thank you so much!

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

その他の回答 (2 件)

madhan ravi
madhan ravi 2020 年 12 月 27 日
terms = 1 ./ (n( : ) .^ x) % < 2016b 1 ./ bsxfun(@power, n( : ), x)
  1 件のコメント
Mohsin Shaikh
Mohsin Shaikh 2020 年 12 月 28 日
Thanks a lot!

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


Luigi Emanuel di Grazia
Luigi Emanuel di Grazia 2020 年 12 月 27 日
Shouldn't it be power(x,n)?

カテゴリ

Help Center および File ExchangeConvert Image Type についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by