Error with matrix assignment - matlab

Good evening to all,
I would like to affect values of a matrix B to others differents matrix C.
Then i try this code:
B=imread("deformation_somb.jpg");
xc=pixel_x1;
yc=pixel_y1;
% where [nr,nc,channels]= size([B])
% pixel_x1=(nc/2) & pixel_y1=(nr/2);
j=nr-yc;
i=xc;
i_c=1;
j_c=1;
C_horizontale_droite=[];
C_horizontale_gauche=[];
C_verticale_haut=[];
C_verticale_bas=[];
i_nouveau_h=i;
i_nouveau_b=i;
j_nouveau_d=j;
j_nouveau_g=j;
while(i_nouveau_h!=nr-1 || i_nouveau_b!=0 || j_nouveau_g!=0 || j_nouveau_d!=nc-1)
C_horizontale_gauche(1,j_c,:)=B(i,j_nouveau_g,:);
C_horizontale_droite(1,j_c,:)=B(i,j_nouveau_d,:);
C_verticale_haut(1,j_c,:)=B(i_nouveau_h,j,:);
C_verticale_bas(1,j_c,:)=B(i_nouveau_b,j,:);
i_nouveau_h = i_nouveau_h+1;
i_nouveau_b = i_nouveau_b-1;
j_nouveau_d = j_nouveau_d+1;
j_nouveau_g = j_nouveau_g-1;
j_c=j_c+1;
endwhile
distance_pixel_gauche_centre = find(C_horizontale_gauche=C_horizontale_droite!=0)
distance_pixel_droite_centre = find(C_horizontale_droite=C_horizontale_gauche!=0)
distance_pixel_haut_centre= find(C_verticale_haut=C_verticale_bas!=0)
distance_pixel_bas_centre= find(C_verticale_bas=C_verticale_haut!=0)
But for the first affect of matrix :
C_horizontale_gauche(1,j_c,:)=B(i,j_nouveau_g,:);
I have an error message :
error : LG : Subscript indices must be either positive integers less than 2^31 or logicals.
Then i verify indices they are positive. I give you an example :
For an image 700*700 RGB, nr=nc=700.
Then j=700-350=350, i =350
So, j_nouveau_g=350.
Thus, the first expression should sent to Octave this one:
`C_horizontale_gauche(1,1,:)=B(350,350,:)`
... Well.. Why octave send me an error?
Thx for your answers.
Best Regards
Julien

Related

How to overcome indefinite matrix error (NbClust)?

I'm getting the following error when calling NbClust():
Error in NbClust(data = ds[, sapply(ds, is.numeric)], diss = NULL, distance = "euclidean", : The TSS matrix is indefinite. There must be too many missing values. The index cannot be calculated.
I've called ds <- ds[complete.cases(ds),] just before running NbClust so there's no missing values.
Any idea what's behind this error?
Thanks
I had same issue in my research.
So, I had mailed to Nadia Ghazzali, who is the package maintainer, and got an answer.
I'll attached my mail and her reply.
my e-mail:
Dear Nadia Ghazzali. Hello Nadia. I have some questions about
NbClust function in R library. I have tried googling but could not
find satisfying answers. First, I’m so grateful for you to making
this awsome R library. It is very helpful for my reasearch. I tested
NbClust function in NbClust library with my own data like below.
> clust <- NbClust(data, distance = “euclidean”,
min.nc = 2, max.nc = 10, method = ‘kmeans’, index =”all”)
But soon, an error has occurred. Error: division by zero! Error in
Indices.WBT(x = jeu, cl = cl1, P = TT, s = ss, vv = vv) : object
'scott' not found So, I tried NbClust function line by line and
found that some indices, like CCC, Scott, marriot, tracecovw,
tracew, friedman, and rubin, were not calculated because of object
vv = 0. I’m not very familiar with argebra so I don’t know meaning
of eigen value. But it seems to me that object ss(which is squart of
eigenValues) should not be 0 after prodected.
So, here is my questions.
I assume that my data is so sparse(a lot of zero values) that sqrt(eigenValues) becomes too small, is that right? I’m sorry I
can’t attach my data but I can attach some part of eigenValues and
squarted eigenValues.
> head(eigenValues)
[1] 0.039769880 0.017179826 0.007011972 0.005698736 0.005164871 0.004567238
> head(sqrt(eigenValues))
[1] 0.19942387 0.13107184 0.08373752 0.07548997 0.07186704 0.06758134
And if my assume is right, what can I do for this problems? Only one
way to drop out 7 indices?
Thank you for reading and I’ll waiting your reply. Best regards!
and her reply:
Dear Hansol,
Thank you for your interest. Yes, your understanding is good.
Unfortunately, the seven indices could not be applied.
Best regards,
Nadia Ghazzali
#seni The cause of this error is data related. If you look at the source code of this function,
NbClust <- function(data, diss="NULL", distance = "euclidean", min.nc=2, max.nc=15, method = "ward", index = "all", alphaBeale = 0.1)
{
x<-0
min_nc <- min.nc
max_nc <- max.nc
jeu1 <- as.matrix(data)
numberObsBefore <- dim(jeu1)[1]
jeu <- na.omit(jeu1) # returns the object with incomplete cases removed
nn <- numberObsAfter <- dim(jeu)[1]
pp <- dim(jeu)[2]
TT <- t(jeu)%*%jeu
sizeEigenTT <- length(eigen(TT)$value)
eigenValues <- eigen(TT/(nn-1))$value
for (i in 1:sizeEigenTT)
{
if (eigenValues[i] < 0) {
print(paste("There are only", numberObsAfter,"nonmissing observations out of a possible", numberObsBefore ,"observations."))
stop("The TSS matrix is indefinite. There must be too many missing values. The index cannot be calculated.")
}
}
And I think the root cause of this error is the negative eigenvalues that seep in when the number of clusters is very high, i.e. the max.nc is high. So to solve the problem, you must look at your data. See if it got more columns then rows. Remove missing values, check for issues like collinearity & multicollinearity, variance, covariance etc.
For the other error, invalid clustering method, look at the source code of the method here. Look at line number 168, 169 in the given link. You are getting this error message because the clustering method is empty. if (is.na(method))
stop("invalid clustering method")

triple sum in matlab

I want to compute the following sum :
I have tried using the following code :
I = imread('C:\Users\Billal\Desktop\image.png');
[x,y,z]=size(I);
x=(1:x) ;
y=(1:y) ;
z=(1:z) ;
Fx=ones(size(x));
Fy=ones(size(y));
Fz=ones(size(z));
X=x*Fy';
Y=Fx*y';
Z=z*Fz';
f=I(X,Y,Z);
sum1 = sum(f(:));
[x1,y1,z1]=size(I);
total = sum1/(x1*y1*z1);
But the result is 0 . I could not figure out where is the problem ? I am following this tutorial .
https://www.mathworks.com/matlabcentral/newsreader/view_thread/126366
Please help me to solve this question .
You can do this in a single step:
result=1/prod(size(I))* sum(I(:));
In the end, the equation just adds up values of the whole image.
The question you link to needs to sum over values of x and y. You don't, you just need to sum over indexes, thus there is no need of all those Fx,Fy things

How to save parts of linprog solutions

I am solving a serie of linear programing problems using linprog by indexing each problem in a for-loop:
from scipy.optimize import linprog
for i in range(1,N):
sol[i] = linprog(coa3[N][0], A_ub = coa4[i], b_ub = chvneg[i], options= {"disp": True})
I would like to save in a list (still indexed over i) the function minimization result and the array displaying the values of the variables. I guess I need to add in the for-loop something like minfval[i] = ??? and xval[i] = ???, but actually I don't know how to extract these values from the results provided by linprog. Any suggestions? Thanks a lot.
Consider reading the docs as it's pretty clearly explained what exactly linprog returns.
The good thing is, that you are actually storing these values with your code already because you are storing the whole scipy.optimize.OptimizeResult.
It's now just a matter of accessing it:
from scipy.optimize import linprog
for i in range(1,N):
sol[i] = linprog(coa3[N][0], A_ub = coa4[i], b_ub = chvneg[i], options= {"disp": True})
# iterate over solution-vectors
for i in range(1,N):
print(sol[i].x)
# iterate over objectives
for i in range(1,N):
print(sol[i].fun)
You should also check out the field success just to be safe!
Extraction of the docs (link above) on what is contained in linprog's result:
x : ndarray
The independent variable vector which optimizes the linear
programming problem.
fun : float
Value of the objective function.
slack : ndarray
The values of the slack variables. Each slack variable corresponds
to an inequality constraint. If the slack is zero, then the
corresponding constraint is active.
success : bool
Returns True if the algorithm succeeded in finding an optimal
solution.
status : int
An integer representing the exit status of the optimization::
0 : Optimization terminated successfully
1 : Iteration limit reached
2 : Problem appears to be infeasible
3 : Problem appears to be unbounded
nit : int
The number of iterations performed.
message : str
A string descriptor of the exit status of the optimization.

Find value in vector "p" that corresponds to maximum value in vector "r = f(p)"

As simple as in title. I have nx1 sized vector p. I'm interested in the maximum value of r = p/foo - floor(p/foo), with foo being a scalar, so I just call:
max_value = max(p/foo-floor(p/foo))
How can I get which value of p gave out max_value?
I thought about calling:
[max_value, max_index] = max(p/foo-floor(p/foo))
but soon I realised that max_index is pretty useless. I'm sorry asking this, real beginner here.
Having dropped the issue to pieces, I realized there's no unique corrispondence between values p and values in my related vector p/foo-floor(p/foo), so there's a logical issue rather than a language one.
However, given my input data, I know that the solution is unique. How can I fix this?
I ended up doing:
result = p(p/foo-floor(p/foo) == max(p/foo-floor(p/foo)))
Looks terrible, so if you know any other way...
Once you have the index, use it:
result = p(max_index)
You can create a new vector with your lets say "transformed" values:
p2 = (p/foo-floor(p/foo))
and then just use find to find the max values on p2:
max_index = find(p2 == max(p2))
that will return the index or indices of p2 with the max value of that operation, and finally just lookup the original value in p
p(max_index)
in 1 line, this is:
p(find((p/foo-floor(p/foo) == max((p/foo-floor(p/foo))))))
which is basically the same thing you did in the end :)

Matlab: Loop issue

This is quite a simple issue, but I've been struggling with it. sortedd and sortedfinal_d are 8 x 1000 Matrices and I am using the loop below to check if any of the elements in sortedfinal_d lies between two consecutive elements of sortedd, in terms of magnitude. I'm doing this along each row. overall_p is a 8 x 1000 Matrix as well, but at the end of this process I end up having final_p as a Matrix of Zeros. I don't know why this is.
for k=2:1000
for s=1:1000
for j=1:8
if sortedd(j,k) > sortedfinal_d(j,s) && sortedfinal_d(j,s) > sortedd(j,k-1)
final_p(j,s) = overall_p(j,k);
end
end
end
end
EDIT: Added data for the inputs as shown below:
sortedd (first four columns) =
0.219977361620113 0.219996752039812 0.220344444223787 0.220593274018691
0.272807483153955 0.273682693068593 0.273846498221277 0.274060049642900
0.327201460264565 0.327375792227635 0.327572790857546 0.327856448530021
0.380389118311424 0.380845274148177 0.380893687870765 0.381015090963159
0.434832574575088 0.434860658844550 0.435021604722982 0.435119929919457
0.487119089589798 0.488128501559782 0.488207451439073 0.488430455768512
0.540652551559395 0.541303305046034 0.542195194863130 0.542234381085921
0.595254195563241 0.595296064375604 0.595376090156252 0.595377962767971
sortedfinal_d =
0.182086792394190 0.182406508309366 0.182406508309366 0.182808976400818
0.233058295607543 0.233058295607543 0.233158455616954 0.233158455616954
0.286243848617693 0.286357973626582 0.286918095670684 0.287393171241241
0.336938335090164 0.336938335090164 0.337094505106945 0.337669618738100
0.390287818652551 0.390567879874952 0.390567879874952 0.390670502700602
0.446995120903824 0.447270251510681 0.447452123072880 0.447597175111267
0.501060785098551 0.501060785098551 0.501060785098551 0.501060785098551
0.551311219045087 0.551463923687602 0.551463923687602 0.551653815175502
Thanks a lot
Do you have to use loops to accomplish this?
matching_d = sortedfinal_d(:,1:end-1) < sortedd(:,2:end) ...
& sortedd(:,2:end) < sortedfinal_d(:,2:end);
final_p(matching_d) = overall_p(matching_d);
If you can show us a small sample input (say, 1x5 versions of sortedd and sortedfinal_d) and output (the corresponding matching_d) it would be easier for us to help troubleshoot.
If i set your matrices to random numbers, final_p does return some numbers.
So your code works as is. Post your dataset or at least describe the dataset in some detail, this will make it much easier to diagnose the problem.
I have reduced 1000 down to 10 and re-ordered the iteration variables to i, j, k to make it easier to follow:
sortedd = rand(8, 10);
sortedfinal_d = rand(8, 10);
overall_p = rand(8, 10);
for i=2:10
for j=1:10
for k=1:8
if sortedd(k,i) > sortedfinal_d(k,j) && sortedfinal_d(k,j) > sortedd(k,i-1)
final_p(k,j) = overall_p(k,i);
end
end
end
end
final_p