indexing error, MATLAB - matlab

keep getting an indexing error " ()-indexing must appear last in an index expression"
bascially im trying to create a matrix x made of randn(n,1000000) where every jth row is multiplied by matrix NV(i,j).
%monte carlo simulation
function [y1,y2,y3,y4]= ed1(SNRL,SNRS,SNRH,n) %ed is the energy detection
g1= SNRL:SNRS:SNRH;
g=10.^(g1/10);
beta=0.8; % is the probability pfa, it cannot be more than 1
pf1=zeros(1,length(g));
pd1=zeros(1,length(g));
pf2=zeros(1,length(g));
pd2=zeros(1,length(g));
x=zeros(n,length(g));
y=zeros(n,length(g));
for i=1 : length(g)
for j=1:n
NV=(i,j);
x(j,:) = randn(n,1000000)*sqrt(NV(i,j));
y(j,:)=randn(n,1000000*(j),:)*sqrt(g(i))+x(j,:);
end
%Tgam is the threshold of gamma distribution
Tgam = gaminv((1-beta),n/2,(2/n)*(1+g(i))); %probab of flase detection
pf1(i)= gamcdf(Tgam,n/2,(2/n)*(1+g(i))); %ho
pd1 (i) = gamcdf(Tgam,n/2,2/n); %h1 % prob of detection
pf2(i)= length (find(sum(y.^2)/n<Tgam))/1000000;
pd2 (i) = length (find(sum(x.^2)/n<Tgam))/1000000;
y1=pf1; y2=pd1; y3=pf2; y4=pd2;
end

You have three things giving you errors:
1) NV=(i,j) This syntax will give you an error message. If you are not getting an error message about this line, you have an error in the line calling this code and should post that too. Try NV=zeros(length(g),n); for a temporary fix until you know what NV should be.
2) randn(n,1000000*(j),:) is also bad syntax. Do you mean randn(n,1000000*(j))?
3) x(j,:) = randn(1,10000)*sqrt(NV(i,j));: x as written in your code is not the right size unless g is magically of length 10000.
Hopefully checking these 3 things will give you an idea of what is giving your specific error message (which is not the same as any of the messages these errors gave me.)

Related

How can I access my vectors indices when I am assigning values?

I am trying to code something in Matlab and it involves a lot of accessing elements in vectors. Below is a snippet of code that I am working on:
x(1)=1;
for i=2:18
x(i)=0;
end
for i=1:18
y(i)=1;
end
for i = 0:262124
x(i+18+1) = x(i+7+1) + mod(x(i+1),2);
y(i+18+1) = y(i+10+1) + y(i+7+1) + y(i+5+1) + mod(y(i+1), 2);
end
% n can be = 0, 1, 2,..., 262142
n = 2;
for i = 0: 262142
z(i+1) = x(mod(i+n+1, 262143)); %error: Subscript indices must either be real positive integers or logicals.
end
In the last "for" loop where I am initialising vector z(), I get an error saying: "Subscript indices must either be real positive integers or logicals." However, when I do not suppres z(i+1) by ommiting the semi colon, the program is able to run, and I can see the values of z in the workspace. Why is this?
The code I am writing in Matlab is based upon the series of instructions shown in the image below. However, I can't seem to track down my error which leads to me not being able to access the elements of x() (without not suppressing the output of z()).
I appreciate any ideas :-) Thank you!
The code breaks at that loop last iteration because , for i=262140 you get
(mod(i+n+1, 262143)) = 0
so you cant access x(0) in matlab. the first elements of any variable is x(1).
In addition, and not related to your question, this code doesn't use the advantages matlab has, instead of
for i=2:18
x(i)=0;
end
you can just write:
x(2:18)=0;
etc

Why does Matlab factorial function perceives an integer as a non-integer?

I'm trying to build a function in Matlab which generates a Taylor series around 0 for sine and the user can insert x (the value for which the sine is approximated) and a maximum error. Thus I want the function to check the maximum error and from this maximum it generates the amount of elements in the Taylor series.
I get the following error:
Error using factorial (line 20)
N must be an array of real non-negative integers.
Error in maxError (line 19)
y(x) = y(x) + (-1)^(j) * x^(2j+1)/factorial(2j+1)
Below my code.
function [n] = maxError(x,e);
%Computes number of iterations needed for a given absolute error.
n=1;
while abs(x)^(n+1)/factorial(n+1) >= e
n = n+1;
end
if mod(n,2) == 0
n=n+1;
end
y=#(x) x;
j=1;
while j<n
y(x) = y(x) + (-1)^(j) * x^(2j+1)/factorial(2j+1)
j=j+1;
end
return
I think I get the error because the factorial function can only take up integers, but the way I see it, I am feeding it an integer. Since j=1; and then gets larger by one per iteration, I don't see how Matlab can perceive this as something else than a integer.
Any help is appreciated.
You are using j as an indexing variable, which is also the complex number in Matlab, and your are forgetting a * multiply.
You can use j as a variable (not recommended!) but when you are putting a number in front of it, Matlab will stil interpret is as the complex number, and not as the variable.
Adding the multiplication symbol will solve the issue, but using i and j as variables will give you these hard to debug errors. If you had used a, the error would have been easier to understand:
>> a=10;
>> 2a+1
2a+1
↑
Error: Invalid expression. Check for missing multiplication operator, missing or
unbalanced delimiters, or other syntax error. To construct matrices, use brackets
instead of parentheses.

Matlab invalid vector using lpsolve

I am using a function in Matlab based on lp_solve. In my case, lp_solve is structured as follows:
A = rand (13336,3); %A is made of real numbers between 0 and 1. For this mwe, I thought 'rand' was fine
W = [0; 0; 1];
C = A(:,3);
B = 1E+09;
e = -1;
m= 13336;
xint = linspace(1,13336,13336);
xint = xint';
obj = lp_solve(A*W,C,B,e,zeros(m,1),ones(m,1),xint)
But when I run it, I get this error:
Error using mxlpsolve
invalid vector.
Error in lp_solve (line 46)
mxlpsolve('set_rh_vec', lp, b);
Error in mylpsolvefunction (line 32) %This is my function that uses lp_solve
obj = lp_solve(A*W,C,B,e,zeros(m,1),ones(m,1),xint);
I looked in the documentation, and it say, under the chapter "Matrices" that:
[...] if a dense matrix is provided, the dimension must exactly match the dimension that is expected by mxlpsolve. Matrices with too few or too much elements gives an 'invalid vector.' error. Sparse matrices can off course provide less elements (the non provided elements are seen as zero). However if too many elements are provided or an element with a too large index, again an 'invalid vector.' error is raised.
I did not understand what they mean when they say that the dimension "must exactly match the dimensions that is expected by mxlpsolve". Anyway, since they say that the error my also occur "if too many elements are provided", I tried to "cut" my inputs from 13336 elements to 50 (I am sure it works with 58 and I am quite sure it does also with 2000), but also this way I receive the same error. What may the problem be?

Error in matrix dimension mismatch

I am trying to model a vector data containing 200 sample points denoting a measurement.I want to see "goodness of fit" and after reading I found that this can be done by predicting the next set of values(I am not that confident though if this is the correct way).I am stuck at this since the following code gives an error and I am just unable to solve it.Can somebody please help in removing the error
Error using *
Inner matrix dimensions must agree.
Error in data_predict (line 27)
ypred(j) = ar_coeff' * y{i}(j-1:-1:j-p);
Also,can somebody tell me how to do the same thing i.e get the coefficients using nonlinear AR modelling,moving average and ARMA since using the command nlarx() did not return any model coefficients?
CODE
if ~iscell(y); y = {y}; end
model = ar(y, 2, 'yw');
%prediction
yresiduals=[];
nsegments=length(y);
ar_coeffs = model.a;
ar_coeff=[ar_coeffs(2) ar_coeffs(3)]
for i=1:nsegments
pred = zeros(length(y{i}),1);
for j=p+1:length(y{i})
ypred(j) = ar_coeff(:)' * y{i}(j-1:-1:j-p);
end
yresiduals = [yresiduals; y{i}(p+1:end) - ypred(p+1:end)];
end
In matlab, * is the matrix product between two matrices. That means that the number of columns in the first matrix must equal the number of rows in the second matrix. You might have intended to use .* element by element multiplication. EDIT: For element by element multiplication, the matrices must be the same size. Check the size of your matrices. If they don't fit either of these conditions, something needs to change.

Metropolis algorithm in MATLAB -->> error with function handles

i have a piece of metropolis algorithm:
mB=5.79*10^(-9); %Bohr magnetone in eV*G^-1
kB=0.86*10^(-4); %Boltzmann in eV*K^-1
%system parameters
L=60; %side square grid
L2=L*L; % total number grid position
Tstep=5; %step in temperature change (K)
Maxstep=10; %max number of steps
nmcs=5; % cycle numberof Metropolis algorithm
magnet=NaN(1,Maxstep);%store magnetization in "monte carlo images" of sample
%Creation initial point arrangement of magnetic spins
%Outer parameters
H=100000; %Gauss
T=20; % Kelvin
%Energy alteration in spin-reverse
de =# (i,j) (2*mB*H).*mlat(i,j);
%Metropolis probability
pmetro=# (i,j) exp(-de(i,j)./(kB*T));
%Creation and display of initial lattice
mlat=2*round(rand(L,L))-1;
mtotal=sum(mlat(:))./L2
% Alteration of system with time
for ii=1:Maxstep
for imc=1:nmcs
for i=1:L
for j=1:L
if pmetro(i,j)>=1
mlat(i,j)=-mlat(i,j);
elseif rand<pmetro(i,j)
mlat(i,j)=-mlat(i,j);
end
end
end
end
magnet(:,ii)=sum(mlat(:))./L2;
%figure(ii);
%pcolor(mlat);
% shading interp;
end
m1=mean(magnet)
error=std(magnet) ./sqrt(numel(magnet))
fprintf('Temperature = %d K',T)
figure(13)
plot(magnet(1,:),'b.')
axis([0 10 0 0.5])
grid on
xlabel('i (Configuration) ')
ylabel('M/(N*mB)')
Now,the problem is in figure(13).The values it gives me are around zero (0.05,0.02..).It supposes to give me values around 0.3..
Generally,the graph its ok,It gives me the right "shape"(it has points) but as i said around zero.
I really don't know how to put this post in order to be understood.Maybe i have some mistake in the "magnet"matrix ,i don't know.
Anyway,i don't demand from anybody to check it thoroughly ,i am just asking if with a quick look anyone can help.
ΕDIT--->> Also,sometimes when i run the program ,it gives me :
Undefined function or method 'mlat'
for input arguments of type 'double'.
Error in ==> #(i,j)(2*mB*H).*mlat(i,j)
Error in ==>
#(i,j)exp(-de(i,j)./(kB*T))
Error in ==> metropolis at 39
if pmetro(i,j)>=1
EDIT--->>> I found the "mistake" .In my code in the loops where i have the function "pmetro" i replaced it with the "exp(-(2*mB*H).*mlat(i,j)./(kB*T))" and the program worked just fine!!!
Why it didn't work with calling the "pmetro"??How can i overcome this?Is there a problem with function handles in loops?
Blockquote
I very strongly suggest that you try writing code without using any function handles until you're really familiar with Matlab.
The line
de =# (i,j) (2*mB*H).*mlat(i,j);
is what causes your problems. In Matlab, when you define a function handle that refers to, say, an array, the function handle will use the array as it was at the time of definition. In other words, even though mlat changes inside your loop, mlat(i,j) inside the function de is always the same. In fact, you cannot even run this code unless you have previously defined mlat in the workspace.
You should therefore rewrite the main loop as follows
for iStep = 1:maxStep
for imc = 1:mcs
pmetro = $some function of mlat - this can be calculated using the
entire array as input
%# for each element in mlat (and thus pmetro), decide whether
%# you have to switch the spin
switchIdx = pmetro > 1 | pmetro < rand(size(mlat));
mlat(switchIdx) = -mlat(switchIdx);
end
$calculate magnetization$
end
Also, note that there is a command mean to take the average. No need to sum and then divide by the number of elements.