Error: Array indices must be positive integers or logical values

4 ビュー (過去 30 日間)
Jack McNulty
Jack McNulty 2021 年 12 月 5 日
コメント済み: Voss 2021 年 12 月 5 日
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 件のコメント
Jack McNulty
Jack McNulty 2021 年 12 月 5 日
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));.
Walter Roberson
Walter Roberson 2021 年 12 月 5 日
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)

サインインしてコメントする。

採用された回答

Voss
Voss 2021 年 12 月 5 日
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 件のコメント
Jack McNulty
Jack McNulty 2021 年 12 月 5 日
That seems to do the trick. Thanks a lot I was trying to figure that out for hours.
Voss
Voss 2021 年 12 月 5 日
No problem, glad it worked. Please mark my answer as accepted, if you don't mind.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by