I am trying to write a function which returns a value 1 if the number entered is a power of two, else it returns a value 0.
function val = func_1(num)
while not(num == 1)
if num%2~=0
val=0;
break
end
num=num/2;
val=1;
end
end
But unfortunately, the function always return a value 1. Is there any error in the algorithm or the code? Thanks in advance for any help.
In Matlab, % is the comment character. Everything from that point onwards until the end of the line is ignored. This means that this line if num%2~=0 is not doing what you think it does.
Instead, use the mod function. link. In this case, the line in question becomes if mod(num, 2)~=0.
On a separate note, I suspect there is a much more efficient way of doing this. See, for example, here.
Related
I am trying to create piecewise functions V(t), D(t).
I try to find the piecewise, then I use the piecewise of t to construct functions and plot them.
But it shows "Index exceeds the number of array elements. Index must not exceed 51".
How can I fix it?
I put my code below and I really hope someone can answer it. Thaks!
z=zeros(1,50);
p_i=zeros(1);
p=0.023;
for i=1:50
z(i)=rand;
if z(i)>p
p_i(end+1)=i+z(i);
end
end
n=numel(p_i);
V=zeros(1,n);
w=zeros(1,n);
D=zeros(1,n);
V_op=zeros(1,n);
%get the number of pi
sigma_w0=0.2;
Q=5;
P=2;
Q_op=4;
for i=1:n
if i>1
w(i)=w(i-1)+normrnd(0,sigma_w0);
V(i)=Q*w(i);
D(i)=P*w(i);
V_op(i)=Q_op*w(i);
else
w(1)=2;
V(i)=Q*w(i);
D(i)=P*w(i);
V_op(i)=Q_op*w(i);
end
end
t=0:0.0002:50;
V_p=zeros(size(t));
D_p=zeros(size(t));
V_opp=zeros(size(t));
for m=1:length(t)
t(m)>=p_i(i)& t(m)<p_i(i+1)
V_p(m)=V(i);
D_p(m)=D(i);
V_opp(m)=V_op(i);
end
Yes, if you run your code you'll see it is functional before the last for loop since it is evaluating that in the 1 to 50 range (m=1:length(t)) but your line is printing 51 values so you need to check only the next part and reorganize the idea:
t(m)>=p_i(i)& t(m)<p_i(i+1)
If you print the first part (t(m)>=p_i(i)) it is okay, but check the other part and you'll notice the error. Maybe you can print all your results moving your increment value (+1) and prevent it from exceeding 1 to 51.
I have a error
This is my code en MATLAB
exponential recursive
function sumac=taylorexp(x,n)
if n==0 sumac=1;
else sumac=((x^(n)/factorial(n)))+taylorexp(x^(n-1),n-1));
end
end
Your code both contains a syntax error (you are closing a parenthesis you never opened) and I believe it does not what you want. I suppose you wanted to compute the Taylor's expansion of exp(t) in the point x up to the n-th order. The following code does so:
function sumac = taylorexp(x,n)
if n == 0
sumac = 1;
else
sumac = x^n/factorial(n) + taylorexp(x,n-1);
end
end
At first I say welcome to you.
Our friend #Noah Levenstein answer is true but I think some completion is needed that I couldn't add them as an edit to his answer.
Parenthesis are mismatch. Use #Noah's answer.
Save your function in a taylorexp.m and just call it from another script.
Don't use double (Non Integer) numbers. factorial just work with n=0,1,2,... not with something like 2.2 or something like 6.81.
Using non Integer numbers for n has another problem too: Your recursive function never can satisfy end condition and falls in infinite loop
I think your main problem is #3 or #4 but if not, feel free to comment.
I am not a very hardcore coder in MATLAB, i have learned every thing from youtube and books. This might be a very simple question but i do not know what search for answer.
In MATLAB i am trying to do something like this.
>>[a,b,c] = [1,2,3]
and i want output like this.
>> a = 1
b = 2
c = 3
So Bsically question is that : - User will define the matrix of variables([a,b,c]) in staring of code and during process of the code similar matrix will be displayed and as input a matrix will be asked([1,2,3]). I dont know how do this without writing a loop code in which i will take every single variable from variable matrix and save the value in that variable by eval function.
well above written code is wrong and i know, i can do this with "for" loop and "eval" function.
but problem is that no. of variables(a,b,c) will never be constant and i want know if there exist any in built function or method in MATLAB which will work better than a for loop.
As i told earlier i don't know what to search for such a problem and either this is a very common question.
Either way i will be happy if you can at least tell me what to search or redirect me to a related question.
Please do write if you want any more information or for any correction.
Thank you.
The deal function can do this for a fixed number of inputs:
[A,B,C]=deal(1,2,3)
If you don't know how many inputs you will get beforehand, you have to do some fooling around. This is what I've come up with:
V=[1,2,3,4,5,6,7]
if length(V)>1
for i=1:length(V)
S{i}=['A' num2str(i)];
G{i}=['V(' num2str(i) ')'];
end
T=[S{1} ','];
R=[G{1} ','];
for i=2:length(V)-1
T=[T S{i} ','];
R=[R G{i} ','];
end
T=[T S{length(V)}];
R=[R G{length(V)}];
eval(['[' T ']=deal(' R ')'])
else
A1=V
end
But then dealing with A1, ... , An when you don't know how many there are will be a pain!
This is somehow known as "tuple unpacking" (at least it's what I would search in python!). I could find this thread which explains that you could do this in Octave (I checked and it works in Matlab also). You have to transform the vector into a cell array before:
values = num2cell([1,2,3])
[a,b,c] = values{:}
I have written a function that is the beginning of a Poisson Process
function n_t = PoisProc2(t,tao,SIZE)
n_t=0;
for n=1:SIZE
if t>tao(1,n)
n_t=n_t+1;
end
end
end
tao is simply an array of random doubles of length SIZE. For simplicity we'll say [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,20]
So this functions purpose is to count how many elements of tao that t is greater than for any given t.
This code works fine when I simply write
PoisProc2(3,tao,20);
the answer I get is 19 as expected, but if I write
x=1:.01:20;
y=PoisProc2(x,tao,20);
plot(x,y,'-')
y shows up as 0 in the workspace (I would expect an array of length 1901) and my plot also reads 0. I'm pretty new to Matlab, but this seems like a pretty simply thing I'm trying to do and I must be missing something obvious. Please help!
Your code does not work as you are giving a vector. So your if condition is not working as you expect.
First initialize n_t with a vector :
n_t=zeros(1,length(t))
instead of
if t>tao(1,n)
n_t=n_t+1;
end
Vectorize your expression :
n_t = n_t + (t>tao(1,n))
Cheers
Because x is a vector in your last example, the "if t>tao(1,n)" statement in your function behave totally different from what you think.
This function below should give you the right result.
function ret = PoisProc2(thresholds, vec)
ret = zeros(size(thresholds));
for k = 1:numel(thresholds)
ret(k) = numel(nonzeros(vec > thresholds(k)));
end
Side comments:
Your original function is quite C/Java style. You can see in my function, it's replaced by a one-liner "numel(nonzeros(vec > thresholds(k)))", which is more MATLAB style.
I think this can be done with hist() function. But this probably is easier to understand.
%function [flag] =verify(area)
[FileName,PathName,FilterIndex]= uigetfile('*.tif','Select the signature file');
display(PathName)
m=[PathName,FileName];
area=nor_area(m);
%display(area)
%area=0.8707;
class(area)
flag=0;
extract=xlsread('D:\Project\Image_processing\important\best.xlsx', 'CW4:CW17');
c=numel(extract);
display(c)
l=extract(1);
class(l)
display(l)
for k = 1:c
%x=extract(k);
if (l==area && flag==0)
% display(extract(k));
flag=1;
display(flag)
end
end
display(flag)
The above is my code for verification, i am not able to compare "l==area", even if the values are same am not able to enter inside the loop. If i try passing the value assume l=0.9999 and the area that i obtain to be the same , if i sent l value explicitly it works..!! but if i try using some function and pass the same value it wont work. I have tried checking the type by using class, both returns double.
Can anyone please help me out with this and if this approach is not good, suggest any alternative that may be used.
It is not generally a good idea to compare floats like you are doing (with the == operator) since floats, unlike integer values are subject to round off. See here and here for a discussion on comparing floats in MATLAB.
Essentially you have to check that two floats are 'close enough' rather than exactly equal, which is what == checks for. MATLAB has a built in function eps for determining the floating point precision on your machine, so use that function when comparing floats. See its documentation for more information.
In most cases it is not wise to compare floating point numbers by a == b. Use abs(a-b)<epsilon where epsilonis some small tolerance like 1e-10 instead.