Sum the solution of solve function

Dear friends,
When solving a system of equations by using S=solve()
I got this kind of result
S =
z11: [1x1 sym]
z12: [1x1 sym]
z13: [1x1 sym]
z21: [1x1 sym]
z22: [1x1 sym]
z23: [1x1 sym]
z31: [1x1 sym]
z32: [1x1 sym]
z33: [1x1 sym]
I would like to find the sum of S.
However it cant be done with sum(S) because: Undefined function or method 'sum' for input arguments of type 'struct'
I can do that manually by first, displaying the solutions, S=[S.z11 S.z12 S.z13 S.z21 S.z22 S.z23 S.z31 S.z32 S.z33] after that, I can finally use sum(S) to get the sum of S.
However, I found this is not practical when I have a huge number of solutions in S.
Is there any other way to get the sum of S? Any help will be greatly appreciated.
Thank you very much.
Sincerely,
Leonardo

 Accepted Answer

SC = struct2cell(S);
plus(SC{:})
or
sum(cell2mat(struct2cell(S)))

More Answers (2)

Hi Walter, Thank you for reply.
I tried both of them,
- for this one, SC = struct2cell(S); plus(SC{:})
I got this message:
??? Error using ==> sym.plus Too many input arguments.
- for this one, sum(cell2mat(struct2cell(S)))
I got this message:
Cannot support cell arrays containing cell arrays or objects.
However, converting from structure to cell does work!
I tried this,
SC = struct2cell(S);
for i = 1:9 %9 is the number of solutions in this case
SCS(i) = SC{i};
end
sum(SCS)
and it is working now! Thank you very much for your help. Cant do this without you.
Sincerely,
Leonardo
I can't get Walter's solution to work in my version of matlab (7.8.0.347 (R2009a)). There S is a sym object, and then this works:
S = solve('(x-x1)*(x-x2)*(x-x3)=0');
sum(S)
ans =
x1 + x2 + x3
What versions are you using?

1 Comment

Hi Bjorn,
Im using R2010a
Apparently in my case, sum is not working for input arguments of type 'struct'.
Therefore, I convert 'struct' to 'cell' as I wrote in my previous message.
Thank you for your reply ^^

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!