MATLAB Answers

Kalyne

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

Asked by Kalyne
on 17 Jun 2013

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.

  1 Comment

The problem here is that once you get into your for loop, you create a new variable x which is of size 1*1. In the second iteration of your loop, you are trying to access the second element of this array, which is not available. Try using a different variable to the lhs of the assignment operation.

Products

No products are associated with this question.

2 Answers

Answer by per isakson
on 17 Jun 2013
Edited by per isakson
on 17 Jun 2013

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

  0 Comments


Answer by Kalyne
on 17 Jun 2013

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

  1 Comment

per isakson
on 17 Jun 2013

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.


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply today