I don't know where am I doing wrong in this code.
I wanted to create an array of even nos. so I wrote the following code in matlab:
A=[];
n=2;
while n!=5
if n%2==0
A=[A n];
n++;
else
n++;
end
end
disp(A)
The following gets displayed as output:
2 3 4
I can't understand why all nos. between 1 to 5 are being displayed.
can anyone please explain where am I wrong.......
I think you're going wrong very early. Try this
A = 2:2:8
then go to the Matlab documentation and read about the colon operator. Then forget C and C++ (what's with all those n++ and the other syntax elements from foreign languages ?). Then forget about loops and learn about vectorisation, you'll get a lot more out of Matlab, with a lot less effort, that way.
I don't know where am I doing wrong in this code.
In MATLAB, the not-equal-to operator is ~=; != is invalid MATLAB syntax.
If you want to increment a variable n, you need to write n = n + 1; n++ is invalid MATLAB syntax.
The % character starts a line comment; it is not the modulo operator. Instead, you want to use either the rem function or the mod function (which are equivalent for nonnegative inputs).
Besides, you don't need a loop for creating such a simple row vector, in which elements follow an arithmetic sequence. Just use MATLAB's colon operator:
<start> : <step> : <bound>
or, more simply
<start> : <bound>
where the step is taken as 1.
Here, either
2:2:8
or
2 * (1 : 4)
will do the trick.
Related
I am a newbie in Maple. Could you please help me to convert the following short code from Matlab to Maple:
I=0.0;
for i1=1:3
I(i1,i1,i1,i1)=1.0;
end
I've tried to write it like:
unprotect(I);
I:=0.0;
for i1 from 1 to 3 do
for i2 from 1 to 3 do
for i3 from 1 to 3 do
for i4 from 1 to 3 do
if i1=i2 and i2=i3 and i3=i4 then I[i1,i2,i3,i4]:=1.0;
else I[i1,i2,i3,i4]:=0.0;
end if;
od;
od;
od;
od;
But it gives the following error:
Error, illegal use of an object as a name
Error, illegal use of an object as a name
Can anybody tell me what's wrong?
Thank you,
It'd be easier if you didn't insist on using the name I, which in Maple has the special meaning of the sqrt of -1.
restart;
interface(imaginaryunit=j):
local I:=Array((1..3)$4,datatype=float[8]);
for i1 from 1 to 3 do
I[i1,i1,i1,i1]:=1.0;
end do:
The above produces I as a 4-dimensional Array, where each dimension has a width of three elements. And the three "long diagonal" elements are all initialized to 1.0. And the Array can contain hardware double precision floats. And all the other elements are 0.0 by default.
Is that what you were trying to do?
If you don't insist on calling assigning it to the special name I then things are easier. Eg,
restart;
II:=Array((1..3)$4,datatype=float[8]):
for i1 from 1 to 3 do
II[i1,i1,i1,i1]:=1.0;
end do:
You cannot properly override/disable the special meaning of I merely by unprotecting it. (And even if you could, unprotecting and redefining I is an unworkable idea since a significant portion of Maple commands would then no longer compute properly in the given session.)
Recent versions of Maple allows you to create a so-called top-level "local" instance of that name, which can be used separately from the usual global name I. If you insist on that route, and if your Maple version is recent enough to support that, then you'd probably also want to change the
interface setting for the imaginary unit (sqrt of -1) so that things don't get too confusing. That's why I showed it in the first example above.
But I really think that you'd find things easiest if you just used another name, like II or what have you.
You don't need to put the datatype=float[8] restriction on the Array. But if your subsequent code mimics some (originally) Matlab code then maybe floats are all that will be assigned into the Array. And some operations on Arrays can be much faster, with it. See how it goes.
I am writing a code for some physics problem. I want to simply neglect the terms containing the variable 't' and make my matrix independent of time 't'.
syms t real
syms temp
i=sqrt(-1);
temp=[exp(t*2*i)*exp(-t*5*i) + 12 exp(3*t*i); exp(-3*t*i) exp(-t*2*i)*exp(t*5*i)+8];
what i expect in my out put is
temp= [12 0;0 8];
I am unable to do it. Can any one help me to solve this ?
Thanks in advance.
A couple of comments:
i is already supported as the imaginary number in MATLAB. It is superfluous to declare i = sqrt(-1);. Also real is a function in MATLAB. It basically returns the real part of a complex number defined in MATLAB. Do not make this symbolic. By doing this, you would be shadowing over the function with that variable name.
Don't do syms temp. You are making this variable symbolic, yet you are overwriting its behaviour in the last line of code.
Now, what you mean by "neglect" is to have any values that have t in the expression go to 0. There really isn't an easy way to do this. There's no utility in MATLAB (at least to my knowledge), that can pick through all mathematical expressions in an array or matrix where if there are terms that have a t in it, you should set them to 0.
The only thing I can suggest is if you substitute t = 0, then subtract 1 from all of the elements. This is because when you substitute t = 0 into each expression in your matrix, exp(0) = 1, and so all elements will have a common 1 term due to each expression having an exponential term. Therefore:
out = subs(temp, 't', 0) - 1;
out =
[ 12, 0]
[ 0, 8]
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Matlab - building an array while looping
Matrix of unknown length in MATLAB?
How do you put all of the "a" values together to form a vector?
for i=1:3
a=2+i
end
Also this is maybe a style question but when do you put a semicolon after the end in a for loop such as the one above, also is it proper to put a semicolon after the first line?
You need to index into a, like this:
for ii=1:3
a(ii) = 2+ii;
end
I prefer to use ii as a loop variable to avoid clashing with MATLAB's built-in i. You should also pre-allocate a if you know the size before the start of the loop, like so:
N = 100;
a = zeros(1,N);
for ii=1:N
a(ii) = 2 + ii;
end
Personally, I never put any punctuation after the for ii=1:3 part, except when writing a one-liner FOR loop, like so:
for ii=1:N, a(ii) = 2 + ii; end
Note that you can construct this more efficiently as such:
a=1:3;
a=a+2;
The first line assigns a to be the vector (1,2,3), the 2nd line adds 2 to every element.
"Efficiency" doesn't matter much in such a small vector, but in general you'll get much better mileage out of matlab if you get used to thinking more like this.