Error: Array indices must be positive integers or logical values

17 views (last 30 days)
Jack McNulty
Jack McNulty on 5 Dec 2021
Commented: Benjamin on 5 Dec 2021
I am trying to make a GUI that allows me to make a grid with the dimensions of the grid as inputs. My for loop works outisde of the 'guide' editor to do this, but when I copy and paste it into the GUI code with the proper callbacks, I get an "array indices must be positive integers or logical values" error. Some of my values are not integers and must stay that way. Please let me know what I can do to fix this.
here is the GUI code for just the pushbutton to run the function
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
clc
s=str2double(get(handles.initial_x,'string'));
lowerbound=str2double(get(handles.initial_y,'string'));
f=str2double(get(handles.end_x,'string'));
upperbound=str2double(get(handles.end_y,'string'));
n=str2double(get(handles.slider1,'Value'));
x=linspace(s,f,n);
y=linspace(lowerbound,upperbound,n);
for i=1:n
xi=x;
yi=y(i)*ones(size(xi));
plot(xi,yi,'b')
hold on
end
for i=1:n
yi=y;
xi=x(i)*ones(size(yi));
plot(xi,yi,'b')
hold on
end
xl=s-20;
xu=f+20;
xlim([xl xu]);
  3 Comments
Walter Roberson
Walter Roberson on 5 Dec 2021
As a debugging step, to track down the problem, at the command line give the command
dbstop if error
Then run your code. When the code stops due to the error, at the command line show us a complete copy of the error message, and show us the output of
whos
which ones
which size
disp(i)

Sign in to comment.

Accepted Answer

Benjamin
Benjamin on 5 Dec 2021
Avoid doing str2double on the slider value. Just do this:
n=get(handles.slider1,'Value');
The error happens because str2double returns NaN with numeric input, so n was NaN, so i is NaN in the loop, and you can't index with a NaN.
  2 Comments
Benjamin
Benjamin on 5 Dec 2021
No problem, glad it worked. Please mark my answer as accepted, if you don't mind.

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!