Decimal numbers in a triple for loop

Hi all, I want to run the equation for a range of q variables at an increment such as
q = 0.1:0.1:1;
I need to use a for loop, where actually I include 2 additional for loops:
a & b are 2 cells.
M=10;
for i=1:length(q)
for i1=1:M
for i2=1:M
n_pm(i)=n_pm(i)+exp(-1i*q(i)*(i1-i2))*a{i1}*b{i2};
end
end
n_pmT(i)=n_pm(i)/(2*M)^2;
end
This code however gives me either the error 'Subscript indices must either be real positive integers or logicals' or 'Index exceeds matrix dimensions', depending on how I define q in the loop.
Looking forward for some help!
Thank you in advance.

댓글 수: 1

James Tursa
James Tursa 2018년 3월 21일
It would help if you copy & pasted the entire error message for us, including the offending line.

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

답변 (2개)

James Tursa
James Tursa 2018년 3월 21일

0 개 추천

Have you inadvertently created a variable with the name 'exp' in your workspace? If so, clear it and don't use that name for a variable.

댓글 수: 4

Auryn_
Auryn_ 2018년 3월 21일
Hi, no, that is actually e^(x).
James Tursa
James Tursa 2018년 3월 22일
편집: James Tursa 2018년 3월 22일
Type this at the command prompt:
dbstop if error
Then run your code. When the error occurs the code will pause with all variables intact. Examine them to see what is going on.
The exp( ) still seems like the likely culprit ...
Hi,
the error 'Index exceeds matrix dimensions' appears even if I use:
q = 0.1:0.1:1;
for i=1:length(q)
for i1=1:M
for i2=1:M
n_pm(i)=n_pm(i)+q(i)*(i1-i2)*a{i1}*b{i2};
end
end
n_pmT(i)=n_pm(i)/(2*M)^2;
end
This error:
'Subscript indices must either be real positive integers or logicals' or 'Index exceeds matrix dimensions'
was probably caused by a variable named 'exp' in your workspace.
This error:
'Index exceeds matrix dimensions'
is different, and means exactly what it says. Did you use the dbstop debugging tip I gave you? When the code paused, what were these values:
i
i1
i2
numel(q)
numel(n_pm)
numel(n_pmT)
numel(a)
numel(b)

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

Auryn_
Auryn_ 2018년 3월 22일
편집: Auryn_ 2018년 3월 22일

0 개 추천

Hi,
now it seems to work!
M=10;
q = 0.1:0.1:1;
n_pmT=zeros(length(q),1);
n_pm=zeros(M,M,length(q));
for i=1:length(q)
for i1=1:M
for i2=1:M
n_pm=n_pm+exp(-1i*q(i)*(i1-i2))*a{i1}*b{i2};
end
end
n_pmT(i)=n_pm(i)/(2*M)^2;
end

댓글 수: 2

James Tursa
James Tursa 2018년 3월 22일
Well, it may run but I have my doubts that this code actually does what you want it to. Inside your inner loop you have n_pm=n_pm+etc. Do you realize that the etc part is added to all of the elements of n_pm at each iteration? Is that what you really want?
Auryn_
Auryn_ 2018년 3월 22일
Hi James, I want a sum over the indices i1 and i2. Is that correct in the code? Thanks again!

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2018년 3월 21일

댓글:

2018년 3월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by