arrayfun with different dimensions
17 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dimitri
am 4 Mai 2014
Kommentiert: Jos (10584)
am 7 Mai 2014
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 Kommentar
Star Strider
am 4 Mai 2014
It would help if you posted all your relevant code. Be sure to include your arrayfun call.
Akzeptierte Antwort
Jos (10584)
am 4 Mai 2014
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 ...
0 Kommentare
Weitere Antworten (4)
Jan
am 4 Mai 2014
Start with two simple for loops:
S = 0;
for jj = 1:k
for ii = 1:k-1
S = S + ...
end
end
0 Kommentare
Jos (10584)
am 6 Mai 2014
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 Kommentare
Jos (10584)
am 7 Mai 2014
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)
Siehe auch
Kategorien
Mehr zu Linear Least Squares finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!