Error: Array indices must be positive integers or logical values

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 个评论

Which line is the error being reported for?
If you use the debugger and you dbstop if error then on the line that has the error, what shows up if you give the command
whos
The error is for yi=y(i)*ones(size(xi));, and I'm assuming it would do the same thing for yi=y(i)*ones(size(xi));.
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)

请先登录,再进行评论。

 采纳的回答

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 个评论

That seems to do the trick. Thanks a lot I was trying to figure that out for hours.
No problem, glad it worked. Please mark my answer as accepted, if you don't mind.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

产品

版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by