summation inside a "for loop"

Hi I have a 100x100 matrix, A. I am doing the following:
q=0:0.1:50;sym k;
for j=1:length(q)
B1(j)=sum(exp(q(j)*A(k,1)), k=1..100);
end
for j=1:length(q)
B2(j)=sum(exp(q(j)*A(k,2)), k=1..100);
end
..................................
..................................
for j=1:length(q)
B100(j)=sum(exp(q(j)*A(k,100)), k=1..100);
end
The problem is perhaps with the command but I tried with both sum/symsum and some other variations. But always matlab gives one or the other error.
It would be very helpful if someone could suggest some "correct" command. Thanks a ton.

댓글 수: 1

Walter Roberson
Walter Roberson 2012년 5월 29일
http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F

댓글을 달려면 로그인하십시오.

 채택된 답변

Geoff
Geoff 2012년 5월 29일

0 개 추천

I would expect this to work:
B = zeros(length(q), size(A,2));
for j = 1:length(q)
B(j,:) = sum( exp(q(j)*A) );
end

댓글 수: 3

Geoff
Geoff 2012년 5월 29일
Oh, sorry, I didn't pick up that this is the symbolic toolbox... I have no idea about that. I thought that looked like strange MatLab code. I'll leave my answer just in case it's any use.
Nilanjan Roy
Nilanjan Roy 2012년 5월 29일
thanks a lot man. i think i was unnecessarily using the symsum command where all i needed was "sum". thanks again.
Geoff
Geoff 2012년 5월 29일
Cool. Hope it's clear what's happening... sum will work along a single dimension. By default this is 1. That means it will sum columns. If it's 2, it'll sum rows, and so on.. Whatever you call strips in higher dimensions =) So we can compute the sum for every column at once (giving a 1x100 vector) and then shove that into the matching columns of B for a single row indexed by j. It would probably be more efficient if you flipped the dimensions of B and wrote a whole column at a time, but I kept it consistent with your matrix A for clarity.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

질문:

2012년 5월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by