arrayfun with different dimensions

17 ビュー (過去 30 日間)
Dimitri
Dimitri 2014 年 5 月 4 日
コメント済み: Jos (10584) 2014 年 5 月 7 日
Hi guys, I have the following question.
I am trying to calculate sum_(j=1)^k (sum_(i=1)^(k-1) ( (i+j)! ))
I defined a function f=@(k) sum(factorial(1:k)+factorial(1:k-1))
Then x=1:5 in order to evaluate the sum for the first 5 natural numbers
But arrayfun(f,x) produces a mistake since it says that I have different dimensions. Which is correct.. but why should it be a problem? And how should I evaluate the sum then?
Many thanks,Dimitri
  1 件のコメント
Star Strider
Star Strider 2014 年 5 月 4 日
It would help if you posted all your relevant code. Be sure to include your arrayfun call.

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

採用された回答

Jos (10584)
Jos (10584) 2014 年 5 月 4 日
factorial(1:k) will give you a vector with k values while factorial(1:k-1) will a vector with k-1 values. You simply cannot add vectors of unequal lengths ...

その他の回答 (4 件)

Jan
Jan 2014 年 5 月 4 日
Start with two simple for loops:
S = 0;
for jj = 1:k
for ii = 1:k-1
S = S + ...
end
end

Dimitri
Dimitri 2014 年 5 月 4 日
Guys, thanks a lot for all your comments. I understand the problem of unequal length, and so was looking for an alternative formulation. Jan thank you, I'll try it tomorrow. If it would not work I put the code, star strider.

Dimitri
Dimitri 2014 年 5 月 5 日
編集済み: Dimitri 2014 年 5 月 5 日
Hi again. I decided to put the code to make it more clear. I have a simple case of a double sum where the first sum is running from 1..k, the second from 1..l, where k,l might have different sizes. The sum refers to factorial of (i+j):
sum_(i=1)^k sum_(j=1)^l (i+j)!
Ok, so here I define the sum:
f=@(k,l) sum( factorial((1:k)+(1:l)) )
x=1:5
y=1:4 %say, I want to evaluate the sum where the first index runs utp 5 and the second up to 4 Then:
arrayfun(f,x,y)
What am I doing wrong? Maybe I have to define differently the matrix (x,y) which has to be assigned to the sum?
Many thanks!

Jos (10584)
Jos (10584) 2014 年 5 月 6 日
So you want 20 sums in total (5 values of x combined with 4 values of y)?
x = 1:5
y = 1:4
[XX,YY] = ndgrid(x,y)
f = @(k) sum(factorial((1:XX(k))+(1:YY(k))) )
S = arrayfun(f,1:numel(XX))
  3 件のコメント
Dimitri
Dimitri 2014 年 5 月 7 日
Hi Jos, unfortunately it still shows the same mistake as before: that the "matrix dimensions must agree".
Jos (10584)
Jos (10584) 2014 年 5 月 7 日
Oops. Yes, of course, because again you want to add two vectors that are not equally long. This means that your formula is not right! Can you split your formula into sub-formulaes like this, and show the expected output for each step when you specify a specific a and b?
a =
b =
c = a + b % !! this errors when a and b do not have the same number of elements
d = factorial(c)
e = sum(d)

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

カテゴリ

Help Center および File ExchangeLinear Least Squares についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by