"Index in position 2 is invalid. Array indices must be positive integers or logical values" when performing a for loop
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (1)
DGM
on 19 Jan 2022
Edited: DGM
on 19 Jan 2022
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)
Either way works
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!