Hello Everyone. I have recently shifted to Julia from matlab. Storing data in julia with for loops has been a trouble for me
Here, is the simple matlab code. I would appreciate if anyone could help me out the conversion in julia.
y=zeros(11,1)
for i=0:0.1:1
y(:,1)=sin(2*i)
end
This code in matlab gives we a column vector of y from 0 to 1 in steps of 0.1.
Please help me out how can I do this in julia .
Thanks!
First of all welcome to the forum and great that you start with Julia I did this transition a few years ago and I like Julia still (and Matlab even less).
A small side note: If you put your code into three backticks like
```
My Code
```
It looks like
My Code
Which is nicer to read.
Then I think you might have meant to type y(i,1) = I? otherwise you always set the whole vector to I (and the end one is a vector of ones. The Matlab variant can also be done with y =( 0:0.1:1)'(the (...)' to get the column vector you have.
As Adriel wrote, in Julia 0:0.1:1 gives you an iterator – that is, if you only need it to run through something (another for for example) you avoid allocating the memory.
The collect(0:0.1:1) says, that it should be collected into a vector.
I hope that explanation helps and have fun in learning Julia.
Uh then it gets nice. You can use several ways (and a for loop it the boring way)
DNF already mentioned the first, . is the elementwise-operator, so sin.(0:0.1:1) is apply sin to even element of the 0:0.1:1 (it gets collected on the way) – indeed the . operator (do something for even element of a vector/matrix) is one of my favourite features, it works with all functions (even your own) so that makes a lot of things nicer.
BTW, 0:0.1:1 itself isn’t just an iterator. It’s a real vector that can be used for everything an ordinary vector can be used for, with one exception: it’s immutable, meaning you cannot change its values.
In 99% of cases you don’t need to use collect on it to make it a ‘real vector’, just use 0:0.1:1 directly for whatever you want.
y=zeros(11,1);
for i=1:1:11
j = (i-1)/10;
y(i,1)=sin(2*j);
end
This is how it should be written in MATLAB. Btw, I just decided to shift from Matlab (had written only a few codes, anyway) to Julia for comp. biol. work, though Matlab will probably still be my language of choice for differential equations.
Speed. especially on non vectorized operations, such as for loops. The julia diffeq stack together with the SciML stack is probably the best there is, in both ease of use, versatility and speed on the area. There are many others, but other people can give them.
Ok. TY gbaraldi and jling. Yes speed is certainly a factor. I hope in terms of accuracy Julia should be as good as MATLAB, or at least not too far behind. That would make me switch to Julia for DEs as well.