Matlab cosine mistake [closed] - matlab

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've got some problem while equaling such function as:
function czeb()
k = 1:1:5;
Xk = cos( (pi*(k-0.5))/5);
CN(5,Xk)
end
function c = CN(N,x)
a=N*acos(x); % a is equal correct
c = cos(a); % buc c not, why?
return
end
If I view variable a inside CN function I receive
a=[1.5708, 4.7124, 7.8540, 10.9956, 14.1372]
which is correct bun next step in CN function is to calculate cos(a).
In this step I receive incorrect value of cos(a).
It should be
cos(a) = 1.0e-04 *[-0.0367,0.1102,-0.1837,0.2571,-0.3306]
but it is 1.0e-15 * [-0.8269,-0.1837,0.3062,-0.4286,0.5511] and I don't know why...

There is a very simple explanation, and you function is not wrong.
a=[1.5708, 4.7124, 7.8540, 10.9956, 14.1372]
is equal to pi/2 + k * pi. When you take the cosine of a, you will just get zeros. 1.0e-15 * 0.8269 is essentially zero (floating point arithmetic, and rounding errors).

I think, I understand your. Have you have create expected values manual, like cos(1.5708)? If yes, then you will always receive different results with results made by your computer. So, I think, your expected values of array a are incorrect.
First, enable long number format in the MATLAB/Octave:
format long;
After that, if you display your a array, you will see the similar output:
> a
a =
1.57079632679490 4.71238898038469 7.85398163397448 10.99557428756428 14.13716694115407
As you see at this step, your expected values and computed values by MATLAB/Octave are different. Than, if you do cos(1.57079632679490) the result will like -3.49148336110938e-15 and, as you see, this is near to the result of cos(a(1)): -8.26948102009006e-16. This means, that your stored number is different with that you see in the output.
To instead receive the same results as you expect - round your a to the fourth number after comma:
a = round(a*10000)/10000;
With this the computed results should be near to your expected results.

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.

How to define a function with a matrix [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 3 years ago.
Improve this question
I want to define a two variables function g so that g(x,y) be a 2*2 matrix. To do this, I define g(x,y)=[1,1;x,y] but when I put g(1,1) I don't get any answer. How can I evaluate to g?
The code g(x,y)=[1,1;x,y] itself will not do anything. I assume that your expect result will be g=[1,1,1,1]? Therefore you should do as follow:
g=g_func(1,1);
disp(g)
function g=g_func(x,y)
g=[1,1;x,y];
end
It's not that different from the previous answer, but perhaps an anonymous function would meet your needs:
>> g = #(x,y)[1,1;x,y];
>> g(5,6)
ans =
1 1
5 6
Alternatively, if you want g to accept only one input (i.e. a 2-element vector, instead of two scalars), you could do:
g = #(x)[1,1;x(1),x(2)];
% or
g = #(x)[1,1;x(:).'];

Derivative of a function in Matlab [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 5 years ago.
Improve this question
I tried to take the derivative the function, but I can't find my mistake:
syms x
A = -1.6*x^2+18.7*x+3.4
This returns (187*x)/10 - (8*x^2)/5 + 17/5.
Then, diff(A) yields 187/10 - (16*x)/5.
There is no mistake here. The derivative of a second degree polynomial is a first degree polynomial... hence the variable x is still present in the result and you cannot evaluate it numerically unless you give a value to x:
vpa(subs(diff(A),x,4)) % evaluates the derivative for X=4, yields 5.9
If you want to reduce your function to a scalar value, a second order derivative must be taken:
vpa(diff(A,2)) % this returns: -3.2
Finally, if you just feel that the numerical parts of the result are "messy" and should be evaluated, you can call the vpa function on the derivative:
vpa(diff(A)) % this returns: 18.7 - 3.2*x

Matlab Matrix Dataset Comparison and Certain Output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
if I have matrices A & B: A=[400(rows)x60(columns)] B=[150x60] (Note:That matrix B has fixed columns=60, but the rows are variable could change from 1-400)
I will enter these two matrices into matlab, matrix A is fixed and uploaded to matlab as an excel file, while matrix B is measured directly from the code.(Note:Both matrices contain numerical values)
Now what I want help with is the following: I want to compare the data I'm getting from matrix B with matrix A CONTINUOUSLY, if the values in B are CLOSE (NOT NECESSARILY EQUAL) to the values of A then the matlab outputs lets say True. If the values in B are NOT CLOSE or completely distant from the values of A, then output False. (Note: I don't know but maybe we should use a certain threshold to determine the range of closeness of values between A and B, if we should have a certain threshold, lets say the threshold should be 70%)
Please if anyone has an answer or could help, I need the program. I'm using Matlab 2014a. Thanks in advance.
Easy!.
Suppose you have your matrix in the file A.xlsx,sheet Sheet1 and the matrix B in matlab already.
Also, let's say that, under this context, that CLOSE is some operator between A and B, up to the m-th row, for example the norm, with m taking any value from 1 to 400.
Norm(A-Bm)=|A-Bm|= SUM_i=1^m SUM_j=1^60 (a(i,j)-bm(i,j))^2
Let's define a threshold, for example 0.1*Norm(An)*Norm(Bn).
Hence, the code for that is the following:
function result=matrixcomparison(Bm)
% Read A Matrix
A=xlsread('A');
[ma,na]=size(A); %ma is always 400, na is always 60
[mb,nb]=size(Bm); %mb is variant, na is always 60
% Make a Projection Matrix
Am=A(1:mb,1:nb);
%Compute the norm
normABm=norm(Am-Bm);
%Compare
if (normABm>0.1*norm(Am)*norm(Bm))
disp('Matrices are different.');
result= 0;
else
disp('Matrices are equal.');
result= 1;
end
You save the above code under the file matrixcomparison.m
Of course, this dont have any 'Continuous' comparison. which you should make on the following sense:
for m=1:400
% Read B
<<Calculate B for m>>
% Calculate Norm
result(m)=matrixcomparison(Bm);
end
% Plot the results
plot(results);
You paste the second above code onto another Script and just run it.
Cheers,...

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