"Index in position 2 is invalid. Array indices must be positive integers or logical values" when performing a for loop

조회 수: 1(최근 30일)
Jamie Tse
Jamie Tse 2022년 1월 19일
편집: DGM 2022년 1월 19일
Hi guys,
As you will be able to tell I am relatively new to Matlab. I have created an array "xrange" with 1 row, 99 elements. It has values ranging from around -7 to 3.5. UI(,) is a matrix of zeroes, which I am trying to fill the first column of using the loop below (N is a pre specified integer), where alpha = 0.25. Everytime I try to do this, i get the error stated in the question title. Please could someone give me some advice on where I may be going wrong?
for j = 1:N-1
UI(j,0) = exp(-alpha*xrange(j))*max(exp(xrange(j)) - K,0);
end
for j=1:N-1
UI(j,0) = exp(-alpha*xrange(j))*max(exp(xrange(j))-K,0);
end
Index in position 2 is invalid. Array indices must be positive integers or logical values.
Any help would be hugely appreciated, Thanks

답변(1개)

DGM
DGM 2022년 1월 19일
편집: DGM 2022년 1월 19일
MATLAB uses 1-based indexing, so UI(j,0) isn't a valid index. You can just use 1 for the first column.
The loop isn't really necessary.
xrange = 10.5*rand(1,99)-7;
alpha = 0.25;
K = 1; % idk what this is
N = 10; % some integer <=100
% use a loop to assign column 1 one row at a time
for j = 1:N-1
UI(j,1) = exp(-alpha*xrange(j)) * max(exp(xrange(j))-K,0);
end
% or assign the whole column at once
idx = 1:N-1;
UI2(:,1) = (exp(-alpha*xrange(idx)) .* max(exp(xrange(idx))-K,0));
% show that the results are the same
immse(UI,UI2)
ans = 0
Either way works

Community Treasure Hunt

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

Start Hunting!

Translated by