Matlab problem - index out of bounds because numel(temp3)=0

In summary, the conversation is about a user trying to use a Matlab program called f2matlab to convert Fortran 90 code to MATLAB code. However, the user keeps getting an error regarding the variable temp3 being an empty matrix. Another user suggests that the code may need to be initialized with zeroes. The conversation then shifts to another user experiencing a similar issue with the code, and the author of the code responds with a fix and mentions that the code cannot handle structures. The conversation then switches to a different topic about a user trying to use a program called MMFM to model traffic, but encountering an error with the variable flambda being out of bounds. The user shares their code and asks for help in fixing the issue.
  • #1
cammo12
9
0
Hi,

I am using a Matlab program called f2matlab, which converts fortran 90 code to MATLAB code.

But I keep on getting the following error:

Attempted to access temp3(1); index out of bounds because numel(temp3)=0.


Does anyone know what this error relates to? :uhh:

Thanks in advance.
 
Physics news on Phys.org
  • #2
Your variable temp3 is an array and as your program loops through the code it is finding that your array index is too large, i.e. you have declared the variable to be an array of length 2 and your code says to loop through it 3 or more times.
 
  • #3
Thanks.

It is strange because the program will work fine with some fortran code I have, but then not with other code. I just don't know why! Back to pulling my hair out...
 
  • #4
Specifically, it's trying to access the first element of temp3. However, temp3 is empty - no elements, hence numel(temp3)=0.

Somewhere in your code, you probably want to initialise temp3 - even if it's with zeroes.
 
  • #5
It is throwing up the error on this line of code:

temp3=temp3(temp3>temp4); temp2=temp3(1)-1;

what does temp3(temp3>temp4) mean?

Sorry about all these stupid questions :frown:
 
  • #6
It means to make a new temp3 which contains elements such that temp3>temp4, where temp3 (the array that will be overwritten by a new temp3) and temp4 are arrays.
 
  • #7
always remember tha tmatlab works with vectors/matrices in regards to its variables.
The equation that may be causing the error is

temp2=temp3(1)-1

Separate that line into 2 lines...and see if it is...if it is then print temp3 (using fprintf or disp, both are your friends, fprintf>disp)
 
Last edited:
  • #8
neurocomp2003 - yes I have tried this and it is temp2=temp3(1)-1 that is the problem.

print temp3 = 0.

still trying to figure out why temp3 is zero... back to the code :grumpy:
 
  • #9
Is that zero or empty?

If zero, there's no problem calling temp3(1).

If empty, there is a problem.

ps: try help keyboard for quick and convenient debugging needs.
 
  • #10
temp3 = Empty matrix: 1-by-0

The code I am using has been tried and test by thousands of people - you can download from the MATLAB website.

But for some reason I am getting this error with some of the code I am using.
 
  • #11
cammo12 said:
temp3 = Empty matrix: 1-by-0

The code I am using has been tried and test by thousands of people - you can download from the MATLAB website.

But for some reason I am getting this error with some of the code I am using.
What's the code?
 
  • #13
OK - glad it's fixed - I also see from the comments that the f2matlab function isn't very robust.
 
  • #14
Hi,

I'm from brazil.
I'm using a Matlab program called MMFM, which calculates the number of states in a Markov chain fluid.

But I keep on getting the following error:

? Attempted to access flambda(4); index out of bounds because numel(flambda)=3.

Error in ==> MMFM>birthdeath at 89
lambda_i=flambda(i);

Error in ==> MMFM at 48
[tjump, state] = birthdeath(npoints, fl, fm, A);

My code is going in loop, how can I fix this?

Thanks.

The code:
function [state,R]=MMFM(pkts,a,N,M,npoints)

%Parâmetros:
%pkts=Série de tráfego a ser modelada
%a=proveniente da modelagem da função de autocovariância
%N=número de fontes agregadas
%npoints=tamanho da série sintética gerada
%M=A cadeia de markov possui M+1 estados. Variando de zero a M.
%m=média da série
%v=variância da série
%R=matriz de transições de estados
%Inputs:
%pkts,a,N,M,npoints
%Outputs:
%state, R

m=mean(pkts);
v=var(pkts);

%Modela as probabilidades do tráfego através de uma distribuição binomial
beta=a/(1+(N*((N*m)^2))/(M*N*v));
alfa=a-beta;
A=(N*v)/(N*m)+(N*m)/M;
%Inicializa a matriz de transições de estados
R=zeros(M+1);
%loop para cadeia de markov birth-death
M=M+1; %O programa considera estados {1,2,...,M+1}
for i=1:M
if i<M
R(i,i+1)=(M-i)*alfa;
end
if i>1
R(i,i-1)=(i-1)*beta;
end
R(i,i)=0;
for j=1:M
if abs(i-j)>1
R(i,j)=0;
end
end
end
%Nascimentos
nasc=M*alfa;
fl=[nasc:-alfa:alfa];
%Mortes
morte=M*beta;
fm=[beta:beta:morte];
[tjump, state] = birthdeath(npoints, fl, fm, A);
eixo=[1:npoints];
plot(eixo,state); %%%plota mudanças de estados sem considerar tempos de
%transições
figure;

[i,j]=hist(state,120);
y=i/npoints;
plot(j,y);
hold on
[p,k]=hist(pkts,120);
yy=p/npoints;
plot(k,yy,'r-');
media=mean(pkts);
tamanho=length(pkts);
poiss=poissrnd(media,tamanho,1);
[pp,kk]=hist(poiss,120);
yy=pp/npoints;
plot(kk,yy,'y-');
legend('MMFM','Real','Poisson');
xlabel('Taxa de Chegadas (Pacotes/Segundo)');
ylabel('Probabilidade');
figure;
plot(tjump,state);
xlabel('Tempo(Segundos)');
ylabel('Taxa de Chegadas (Pacotes/Segundo)');

%Chama programa birthdeath
function [tjump, state] = birthdeath(npoints, flambda, fmu,A)
% BIRTHDEATH generate a trajectory of a birth-death process
%
%[tjump, state] = birthdeath(npoints,flambda,fmu)
%Inputs: npoints - length of the trajectory
%Outputs: tjump - jump times
%state - states of the embedded Markov chain

i=1; %initial value, start on level i
tjump(1)=0; %start at time 0
state(1)=i; %at time 0: level i
for k=2:npoints
% compute the intensities
lambda_i=flambda(i);
mu_i=fmu(i);

time=-log(rand)./(lambda_i+mu_i); % Inter-step times:
% Exp(lambda_i+mu_i)-distributed

if rand<=lambda_i./(lambda_i+mu_i)
i=i+1; % birth
else
i=i-1; % death
end %if
state(k)=i;
tjump(k)=time;
end %for i

tjump=cumsum(tjump); %cumulative jump times

state=state-1;
state=state*A;
 
  • #15
Added [ code] and [ /code] tags to format your code.
Christiane said:
Hi,

I'm from brazil.
I'm using a Matlab program called MMFM, which calculates the number of states in a Markov chain fluid.

But I keep on getting the following error:

? Attempted to access flambda(4); index out of bounds because numel(flambda)=3.

Error in ==> MMFM>birthdeath at 89
lambda_i=flambda(i);

Error in ==> MMFM at 48
[tjump, state] = birthdeath(npoints, fl, fm, A);
Look at the fl array that you're passing in the call to birthdeath. Apparently fl has only three elements, and the code in the birthdeath function is attempting to access fl(4), which isn't there.
Christiane said:
My code is going in loop, how can I fix this?

Thanks.

The code:
Code:
function [state,R]=MMFM(pkts,a,N,M,npoints)

%Parâmetros:
    %pkts=Série de tráfego a ser modelada
    %a=proveniente da modelagem da função de autocovariância
    %N=número de fontes agregadas
    %npoints=tamanho da série sintética gerada
    %M=A cadeia de markov possui M+1 estados. Variando de zero a M.
    %m=média da série
    %v=variância da série
    %R=matriz de transições de estados
        %Inputs:
            %pkts,a,N,M,npoints
        %Outputs:
            %state, R        
    
m=mean(pkts);
v=var(pkts);

%Modela as probabilidades do tráfego através de uma distribuição binomial
beta=a/(1+(N*((N*m)^2))/(M*N*v));
alfa=a-beta;
A=(N*v)/(N*m)+(N*m)/M;
%Inicializa a matriz de transições de estados
R=zeros(M+1);
%loop para cadeia de markov birth-death
M=M+1; %O programa considera estados {1,2,...,M+1}
for i=1:M
    if i<M
        R(i,i+1)=(M-i)*alfa;
    end
    if i>1
        R(i,i-1)=(i-1)*beta;
    end
    R(i,i)=0;
    for j=1:M
        if abs(i-j)>1
            R(i,j)=0;
        end
    end
end
%Nascimentos
nasc=M*alfa;
fl=[nasc:-alfa:alfa];
%Mortes
morte=M*beta;
fm=[beta:beta:morte];
[tjump, state] = birthdeath(npoints, fl, fm, A);
eixo=[1:npoints];
plot(eixo,state);   %%%plota mudanças de estados sem considerar tempos de
%transições
figure;

[i,j]=hist(state,120);
y=i/npoints;
plot(j,y);
hold on
[p,k]=hist(pkts,120);
yy=p/npoints;
plot(k,yy,'r-');
media=mean(pkts);
tamanho=length(pkts);
poiss=poissrnd(media,tamanho,1);
[pp,kk]=hist(poiss,120);
yy=pp/npoints;
plot(kk,yy,'y-');
legend('MMFM','Real','Poisson');
xlabel('Taxa de Chegadas (Pacotes/Segundo)');
ylabel('Probabilidade');
figure;
plot(tjump,state);
xlabel('Tempo(Segundos)');
ylabel('Taxa de Chegadas (Pacotes/Segundo)');

%Chama programa birthdeath
function [tjump, state] = birthdeath(npoints, flambda, fmu,A)
% BIRTHDEATH generate a trajectory of a birth-death process
%
 %[tjump, state] = birthdeath(npoints,flambda,fmu)
 %Inputs: npoints - length of the trajectory
 %Outputs: tjump - jump times
 %state - states of the embedded Markov chain

 i=1;     %initial value, start on level i
 tjump(1)=0;  %start at time 0
 state(1)=i;  %at time 0: level i
 for k=2:npoints
    % compute the intensities
    lambda_i=flambda(i);
    mu_i=fmu(i);

    time=-log(rand)./(lambda_i+mu_i);      % Inter-step times:
                                       % Exp(lambda_i+mu_i)-distributed

    if rand<=lambda_i./(lambda_i+mu_i)
      i=i+1;     % birth
    else
      i=i-1;     % death
    end          %if
    state(k)=i;
    tjump(k)=time;
 end              %for i

 tjump=cumsum(tjump);     %cumulative jump times

 state=state-1;
 state=state*A;
 

1. Why am I getting an "index out of bounds" error in Matlab?

This error occurs when you try to access an element in an array or matrix using an index that is outside the bounds of the array. In other words, the index you are trying to access does not exist in the array.

2. What does the "numel" function do in Matlab?

The "numel" function in Matlab returns the number of elements in an array or matrix. It is useful for determining the size of an array or for looping through all the elements in an array.

3. How can I fix an "index out of bounds" error in Matlab?

To fix this error, you will need to make sure that the index you are using to access an element in an array is within the bounds of the array. You can also use the "numel" function to check the size of your array and make sure your index is within that range.

4. Can an "index out of bounds" error be caused by an empty array?

Yes, if you try to access an element in an empty array, you will get an "index out of bounds" error. This is because an empty array has no elements, so there are no indexes to access.

5. How can I prevent "index out of bounds" errors in Matlab?

You can prevent "index out of bounds" errors by carefully checking the size of your arrays and making sure you are using valid indexes to access elements. You can also use conditional statements to check the size of an array before trying to access an element. Additionally, you can use the "isempty" function to check if an array is empty before trying to access elements.

Similar threads

  • MATLAB, Maple, Mathematica, LaTeX
Replies
3
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
2
Views
3K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
3
Views
3K
  • Computing and Technology
Replies
3
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
8
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
4
Views
6K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
1
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
1
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
Back
Top