MATLAB - singularity warning [closed] - matlab

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
when my matlab code gets to the line:
vE(:,:,i)=(mY(:,:,i))\(-mA*(vIs-mG(:,:,i)*vVs));
The following warning comes up:
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate.
RCOND = 1.682710e-16.
Whats wrong?
Full code:
function [ vE, vV_node, vI_node ] = ...
node_analysis( vIs, vVs, mA, mG, mY )
[A,B,N]=size(mY);
vE=zeros(4,1,N);
for i=1:N
vE(:,:,i)=(mY(:,:,i))\(-mA*(vIs-mG(:,:,i)*vVs));
vV_node(:,:,i)=mA'*vE(:,:,i);
vI_node(:,:,i)=mG(:,:,i)*vV_node(:,:,i)+(vIs-mG(:,:,i)*vVs);
end
end
vE=mY^-1 * (-mA*(cIs-mG*vVs))
vE is (4x1xN) size
mY(4x4xN)
mA(4x9)
vIs(9x1)
mG(9x9xN)
vVs(9x1)

When you use the \ operator with a matrix, MATLAB will try and solve the least squares problem to estimate x given y in the equation y = A*x. Depending on the size and shape of A, solving this equation might be easy, hard, or impossible without additional information. It just depends on your particular problem.
As Oli mentioned the comments, this is because your matrix is close to singular or its singular values are close to zero. MATLAB is properly informing you that the MATRIX likely has either unknown information that is going to screw up the answer or that some of the information in the MATRIX is so small compared to other pieces that the small part is going to make solving for x almost impossible and error prone.
Depending on your math background, you might consider the following cod where I create create a matrix with one value very small. This will reproduce your error:
%% Make some data:
randn('seed', 1982);
n = 3;
A = zeros(n);
for ind = 1:n-1
v = randn(n,1);
A = A + v*v';
end
% Last bit is very tiny compared to the others:
A = A + 1e-14*randn(n,1)*randn(1,n);
%% Try and solve Ax=y for x= 1,2,3...
x = (1:n)';
y = A*x
x_est = A \ y
There are various ways to start trying to fix this, usually by reformulating the problem and/or adding some kind of regularization term. A good first try, though, is so add a simple Tikhonov regularization which bumps up all the small values to something reasonable that MATLAB can work with. This may mess up your data but you can plat with it.
Roughly, try this:
tikk = 1e-12;
x_est2 = (A + tikk * eye(n)) \ y
For larger or smaller values of tikk and you will see the error goes away but the solution is to some degree wrong. You might find this acceptable or not.
Note that in my example the answer is quite wrong because I used n=3. As you increase the problem size n you will be better results.
Finally, to begin exploring what is wrong with your matrix A ((-mA*(vIs-mG(:,:,i)*vVs))), you might consider seeing how fast the values s in s=svd(A) decay. Some of them should be quite close to zero. Also, you might look at Tihkonov regularization and what you can do by actually decomposing the matrix into the SVD and scaling things better.

Related

Loop vectorization [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm applying the filtering function in the frequency domain. Because I am working with large amounts of data, I want to vectorize the for loop shown below. Any help would be appreciated.
N = 2^nextpow2(length(signal));
Y = fft(signal,N);
df=1/(N*dt);
freq=0:df:N/2*df-df;
ff=freq./fccutlow;
H=zeros(1,length(N));
for i=2:length(ff)
H(i)= sqrt((ff(i).^(2*nOrder)))./sqrt(((1+ff(i).^(2*nOrder))));
Y(i)= Y(i).*H(i);
Y(length(Y)-i+2)=Y(length(Y)-i+2).*H(i);
end
Y1= (real(ifft(Y,N)))';
Y1=Y1(1:length(signal));
filt_signal(1,:)=Y1;
For vector arithmetic on whole matrix you do not need any indexing, only use array operators, .*, ./, .^. But when only a part of array is used as operand, you need to use one of indexing methods. Keep in mind that all input and output ranges of arrays should be of compatible sizes.
Check parentheses again, but it is something like this:
H = sqrt((ff.^(2*nOrder)))./sqrt(((1+ff.^(2*nOrder))));
Y= Y.*H;
Y(end-((1:length(ff))+2))=Y(end-((1:length(ff))+2)).*H;
An example: Note that it does not matter if the matrices themselves do not have same sizes, but the operands must have compatible sizes:
A = 1:4; % 1x4
B = magic(3); % 3x3
C = zeros(3, 1); % 3x1
C([1 3]) = A(3:end).*B(1:2, 2)';
Although in this example A, B and C have different sizes, but A(3:end) and B(1:2, 2)' are both 1 by 2 and the code runs with no problem. Try to run it and evaluate different parts of code to see how indexing works.

GUI solving equations project

I have a Matlab project in which I need to make a GUI that receives two mathematical functions from the user. I then need to find their intersection point, and then plot the two functions.
So, I have several questions:
Do you know of any algorithm I can use to find the intersection point? Of course I prefer one to which I can already find a Matlab code for in the internet. Also, I prefer it wouldn't be the Newton-Raphson method.
I should point out I'm not allowed to use built in Matlab functions.
I'm having trouble plotting the functions. What I basically did is this:
fun_f = get(handles.Function_f,'string');
fun_g = get(handles.Function_g,'string');
cla % To clear axes when plotting new functions
ezplot(fun_f);
hold on
ezplot(fun_g);
axis ([-20 20 -10 10]);
The problem is that sometimes, the axes limits do not allow me to see the other function. This will happen, if, for example, I will have one function as log10(x) and the other as y=1, the y=1 will not be shown.
I have already tried using all the axis commands but to no avail. If I set the limits myself, the functions only exist in certain limits. I have no idea why.
3 . How do I display numbers in a static text? Or better yet, string with numbers?
I want to display something like x0 = [root1]; x1 = [root2]. The only solution I found was turning the roots I found into strings but I prefer not to.
As for the equation solver, this is the code I have so far. I know it is very amateurish but it seemed like the most "intuitive" way. Also keep in mind it is very very not finished (for example, it will show me only two solutions, I'm not so sure how to display multiple roots in one static text as they are strings, hence question #3).
function [Sol] = SolveEquation(handles)
fun_f = get(handles.Function_f,'string');
fun_g = get(handles.Function_g,'string');
f = inline(fun_f);
g = inline(fun_g);
i = 1;
Sol = 0;
for x = -10:0.1:10;
if (g(x) - f(x)) >= 0 && (g(x) - f(x)) < 0.01
Sol(i) = x;
i = i + 1;
end
end
solution1 = num2str(Sol(1));
solution2 = num2str(Sol(2));
set(handles.roots1,'string',solution1);
set(handles.roots2,'string',solution2);
The if condition is because the subtraction will never give me an absolute zero, and this seems to somewhat solve it, though it's really not perfect, sometimes it will give me more than two very similar solutions (e.g 1.9 and 2).
The range of x is arbitrary, chosen by me.
I know this is a long question, so I really appreciate your patience.
Thank you very much in advance!
Question 1
I think this is a more robust method for finding the roots given data at discrete points. Looking for when the difference between the functions changes sign, which corresponds to them crossing over.
S=sign(g(x)-f(x));
h=find(diff(S)~=0)
Sol=x(h);
If you can evaluate the function wherever you want there are more methods you can use, but it depends on the size of the domain and the accuracy you want as to what is best. For example, if you don't need a great deal of accurac, your f and g functions are simple to calculate, and you can't or don't want to use derivatives, you can get a more accurate root using the same idea as the first code snippet, but do it iteratively:
G=inline('sin(x)');
F=inline('1');
g=vectorize(G);
f=vectorize(F);
tol=1e-9;
tic()
x = -2*pi:.001:pi;
S=sign(g(x)-f(x));
h=find(diff(S)~=0); % Find where two lines cross over
Sol=zeros(size(h));
Err=zeros(size(h));
if ~isempty(h) % There are some cross-over points
for i=1:length(h) % For each point, improve the approximation
xN=x(h(i):h(i)+1);
err=1;
while(abs(err)>tol) % Iteratively improve aproximation
S=sign(g(xN)-f(xN));
hF=find(diff(S)~=0);
xN=xN(hF:hF+1);
[~,I]=min(abs(f(xN)-g(xN)));
xG=xN(I);
err=f(xG)-g(xG);
xN=linspace(xN(1),xN(2),15);
end
Sol(i)=xG;
Err(i)=f(xG)-g(xG);
end
else % No crossover points - lines could meet at tangents
[h,I]=findpeaks(-abs(g(x)-f(x)));
Sol=x(I(abs(f(x(I))-g(x(I)))<1e-5));
Err=f(Sol)-g(Sol)
end
% We also have to check each endpoint
if abs(f(x(end))-g(x(end)))<tol && abs(Sol(end)-x(end))>1e-12
Sol=[Sol x(end)];
Err=[Err g(x(end))-f(x(end))];
end
if abs(f(x(1))-g(x(1)))<tol && abs(Sol(1)-x(1))>1e-12
Sol=[x(1) Sol];
Err=[g(x(1))-f(x(1)) Err];
end
toc()
Sol
Err
This will "zoom" in to the region around each suspected root, and iteratively improve the accuracy. You can tweak the parameters to see whether they give better behaviour (the tolerance tol, the 15, number of new points to generate, could be higher probably).
Question 2
You would probably be best off avoiding ezplot, and using plot, which gives you greater control. You can vectorise inline functions so that you can evaluate them like anonymous functions, as I did in the previous code snippet, using
f=inline('x^2')
F=vectorize(f)
F(1:5)
and this should make plotting much easier:
plot(x,f(x),'b',Sol,f(Sol),'ro',x,g(x),'k',Sol,G(Sol),'ro')
Question 3
I'm not sure why you don't want to display your roots as strings, what's wrong with this:
text(xPos,yPos,['x0=' num2str(Sol(1))]);

Matlab exercise: i just don't get it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given the signals:
f1[n] = sinc[n] {1[n+5]-1[n-5]}
f2[n] = 1-rect[n]
f3[n] = 1[n]-1[n-5]
write a programm in matlab in which you will check the following proprieties:
1)sinc[n]:=sin(phi*n)/phi*n;
2)(f1*f2)[n] = (f2*f1)[n];
3)f1[n]*{ f2[n] + f3[n] } = f1[n]*f2[n] + f1[n]*f3[n];
4)(f1*delta)[n] = (delta*f1)[n] = f1[n];
I'm really really grateful for any tips/ideal on how to solve this problem. :)
sinc[n]:=sin(phi*n)/phi*n;
That certainly isn't Matlab syntax, and the ; at the end makes it not look much like a question either. Anyway, you have two options. Either plot the functions to visually assess equivalence or else check the vectors. I'll demonstrate with this one, then you can try for all the others.
Firstly you need to make a sample n vector which will be your domain over which to test equivalence (i.e. the x values of your plot). I'm going to arbitrarily choose:
n = -10:0.01:10;
Also I'm going to assuming by phi you actually meant pi based on the Matlab definition of sinc: http://www.mathworks.com/help/signal/ref/sinc.html
So now we have to functions:
a = sinc(n);
b = sin(n)./n;
a and b are now vectors with a corresponding "y" value for each element of n. You'll also notice I used a . before the /, this means element wise divide i.e. divide each element by each corresponding element rather than matrix division which is inversion followed by matrix multiplication.
Now lets plot them:
plot(n, a, n, b, 'r')
and finally to check numerical equivalence we could do this:
all(a == b)
But (and this is probably a bit out of scope for your question but important to know) you should actually never check for absolute equivalence of floating point numbers like that as you get precision errors due to different truncations in the inner calculations (because of how your computer stores floating point numbers). So instead it is good practice to rather check that the difference between the two numbers is less than some tiny threshold.
all((a - b) < 0.000001)
I'll leave the rest up to you

Find Audio Peaks in MATLAB [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an audio signal of about the size 7000000 x 1. I have used the peakfinder m file in MATLAB to find the location of all of the peaks in the audio file above a specific threshold. I am now trying to find a frame sized 1000000 x 1 that contains the greatest amount of peaks. I am completely lost on how to do this and any help would be greatly appreciated. Thank you!
Well, all the peak finder function is doing is taking the second derivative and looking for any place where the resulting value is negative. This indicates a local maximum. So you can do something very similar to find any local maximum.
Once you have these indices, you can window the array containing a logical representation of the locations, and count how many peaks are there.
The code below will do what I am saying. It will window across and count the number of peaks found, and return a a vector of the counts, which you can then just find the max of, and then you have the starting index.
clc; close all; clear all;
A = randi(10,[1,100])
plot(A)
hold on
C = diff(diff(A))
indices = find(C < 0)+1;
scatter(indices,A(indices),'r')
temp = zeros(size(A));
temp(indices) = 1;
window = ones(1,5);
results = conv(temp,window,'same');
max(results)
This is of course a pet example, A would be your matrix, and window would be a matrix the length of the range you want to examine, in your case 1000000
Edit
As Try Hard has made note of in the comments below, this method will be fairly susceptible to noise, so what you can do first is run a smoothing filter over the signal before doing any derivatives, something like as follows.
filt = (1/filtLength) * ones(1,filtLength);
A = conv(A,filt,'same')
This is a simple averaging filter which will help smooth out some of the noise

Avoiding loops in MatLab code (barycentric weights)

After having learned basic programming in Java, I have found that the most difficult part of transitioning to MatLab for my current algorithm course, is to avoid loops. I know that there are plenty of smart ways to vectorize operations in MatLab, but my mind is so "stuck" in loop-thinking, that I am finding it hard to intuitively see how I may vectorize code. Once I am shown how it can be done, it makes sense to me, but I just don't see it that easily myself. Currently I have the following code for finding the barycentric weights used in Lagrangian interpolation:
function w = barycentric_weights(x);
% The function is used to find the weights of the
% barycentric formula based on a given grid as input.
n = length(x);
w = zeros(1,n);
% Calculating the weights
for i = 1:n
prod = 1;
for j = 1:n
if i ~= j
prod = prod*(x(i) - x(j));
end
end
w(i) = prod;
end
w = 1./w;
I am pretty sure there must be a smarter way to do this in MatLab, but I just can't think of it. If anyone has any tips I will be very grateful :). And the only way I'll ever learn all the vectorizing tricks in MatLab is to see how they are used in various scenarios such as above.
One has to be creative in matlab to avoid for loop:
[X,Y] =meshgrid(x,x)
Z = X - Y
w =1./prod(Z+eye(length(x)))
Kristian, there are a lot of ways to vectorize code. You've already gotten two. (And I agree with shakinfree: you should always consider 1) how long it takes to run in non-vectorized form (so you'll have an idea of how much time you might save by vectorizing); 2) how long it might take you to vectorize (so you'll have a better sense of whether or not it's worth your time; 3) how many times you will call it (again: is it worth doing); and 3) readability. As shakinfree suggests, you don't want to come back to your code a year from now and scratch your head about what you've implemented. At least make sure you've commented well.
But at a meta-level, when you decide that you need to improve runtime performance by vectorizing, first start with small (3x1 ?) array and make sure you understand exactly what's happening for each iteration. Then, spend some time reading this document, and following relevant links:
http://www.mathworks.com/help/releases/R2012b/symbolic/code-performance.html
It will help you determine when and how to vectorize.
Happy MATLABbing!
Brett
I can see the appeal of vectorization, but I often ask myself how much time it actually saves when I go back to the code a month later and have to decipher all that repmat gibberish. I think your current code is clean and clear and I wouldn't mess with it unless performance is really critical. But to answer your question here is my best effort:
function w = barycentric_weights_vectorized(x)
n = length(x);
w = 1./prod(eye(n) + repmat(x,n,1) - repmat(x',1,n),1);
end
Hope that helps!
And I am assuming x is a row vector here.