index out of bounds error

1 view (last 30 days)
soloby
soloby on 1 Jul 2015
Answered: Brendan Hamm on 1 Jul 2015
Hey all, my code looks something like this.
clear
clc
x = -10:0.1:10;
f1 = trapmf(x,[-2 0 0 2]);
f2 = trapmf(x,[1 3 3 5]);
kvals = 0.05:0.05:1;
for kidx = 1 : length(kvals)
k = kvals(kidx);
index1 = find(abs(f1-k)<10^(-10));
Xidx1{kidx} = x(index1);
Xidx1{20} = [0 0];
index2 = find(abs(f2-k)<10^(-10));
Xidx2{kidx} = x(index2);
Xidx2{20} = [0 0];
A(kidx) = Xidx1{kidx}(1);
B(kidx) = Xidx1{kidx}(2);
C(kidx) = Xidx2{kidx}(1);
D(kidx) = Xidx2{kidx}(2);
end
It works perfectly for what it is, getting lower and upper bounds of my functions f1 and f2.
But for some reason if I change my f1 or f2 functions to something else, I am getting a number of elements error?
Like f2 = trapmf(x,[1 3 3 4])
will give me an error, and I can't seem to figure out why that is?
the exact error message is
Attempted to access Xidx2.%cell(2); index out of bounds because
numel(Xidx2.%cell)=1.
Error in (line 22)
D(kidx) = Xidx2{kidx}(2);

Accepted Answer

Brendan Hamm
Brendan Hamm on 1 Jul 2015
You are using the find function and then assigning values based on that to the variable Xidx2{kidx}. If you use the debugger with the change you mentioned you will notice that on the first run there is exactly one return value for the line:
index2 = find(abs(f2-k)<10^(-10));
Therefore the value being passed in the following assignment is a scalar:
Xidx2{kidx} = x(index2);
Therefore you get an error in the indexing that follows:
D(kidx) = Xidx2{kidx}(2);
There is nothing in this code which will guarantee that there are multiple values which satisfy the inequality:
abs(f2-k)<10^(-10)
You could use an if statement or try-catch block to perform this check for you.
When you encounter these errors, use the debugger , it is your friend.

More Answers (0)

Categories

Find more on Entering Commands 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!