index out of bounds because numel(x)=1.

10 次查看(过去 30 天)
I am trying to create a loop to call different variables at each time but I am getting this message "index out of bounds because numel(x)=1."
What am I doing wrong?
> x(1)=50;
>> x(2)=45;
>> x(3)=89;
>> x(4)=88;
>> for i=1:1:4
x=x(i);
end
??? Attempted to access x(2); index out of bounds
because numel(x)=1.
  3 个评论
Mevlüt Yalaz
Mevlüt Yalaz 2016-7-4
you have to initialize first the dimension of x. Then you get what you want
Walter Roberson
Walter Roberson 2016-7-4
No, that is incorrect, Mevlüt Yalaz . The problem is that one value is extracted from x and that one value is used to overwrite all of x.

请先登录,再进行评论。

采纳的回答

per isakson
per isakson 2013-6-17
编辑:per isakson 2013-6-17
This script
x(1)=50;
x(2)=45;
x(3)=89;
x(4)=88;
disp(x)
for ii=1:1:4
x=x(ii);
disp(x)
end
returns
50 45 89 88
50
Attempted to access x(2); index out of bounds because numel(x)=1.
>>
The vector x is overwritten by the first value of x

更多回答(1 个)

Kalyne
Kalyne 2013-6-17
编辑:Walter Roberson 2016-7-4
Thanks for the answer! I am asking this because I am trying to solve the problem below. But now when I try to run, it appears :
"??? Cell contents reference from a non-cell array object.
Error in ==> TESTAR at 35
problem_statement=problem_statement{i}"
the program:
clear;
run('..\psg_load_libraries');
addpath('..');
clear problem_statement;
problem_statement{1}= textread('problem_DEA_Hospital.txt','%s', 'whitespace', '');
problem_statement{2}= textread('problem_DEA_Hospital2.txt','%s', 'whitespace', '');
% read and print problem statement
for i=1:1:2
problem_statement=problem_statement{i};
problem_statement=problem_statement{i};
fprintf('Problem statement:\n%s', problem_statement);
end
  2 个评论
per isakson
per isakson 2013-6-17
Your text would be easier to read if you format/markup it; use the {}Code button
clear; run('..\psg_load_libraries'); addpath('..');
clear problem_statement;
problem_statement{1}= textread('problem_DEA_Hospital.txt' ...
,'%s', 'whitespace', '');
problem_statement{2}= textread('problem_DEA_Hospital2.txt' ...
,'%s', 'whitespace', '');
for ii=1:1:2
problem_statement=problem_statement{ii};
problem_statement=problem_statement{ii};
fprintf('Problem statement:\n%s', problem_statement);
end
Based on this code, it is not possible (for me) to understand what you want to do. The code says that you want to read two files and write something. Maybe the files each contains a single line.
Walter Roberson
Walter Roberson 2016-7-4
Your line
problem_statement=problem_statement{ii};
takes the ii'th element of problem_statement, and writes that over top of all of problem_statement, so afterwards problem_statement is probably going to be a string instead of a cell array of strings.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Search Path 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by