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

1 次查看(过去 30 天)
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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by