# Rewriting a Matlab code From Matlab to Julia

Hi, I have written this code in Matlab which runs perfectly for me and gives me the plots I needed together with the solutions. I am working in Julia and want to rewrite my code from matlab to Julia but having challenges getting this work. Any help will be greatly appreciated please. Attached is my Matlab code which I want to write in Julia. Can anyone please look at this code and help me rewrite it in Julia. I need help please.

``````

clear
clc
n=7
W=[4 3 5 6 7 6 5]
x=[33 15 2 5 39 17 11]
y=[41 11 4 45 3 26 4]
plot(x,y, 'ko')
hold on
x-y
c=W.*(x-y)
d = norm(c) % this is two norm
x0=sum(W.*x)/sum(W)
y0=sum(W.*y)/sum(W)
Xk=[x0,y0]
hold  on
plot(x0,y0, 'kv')
for r=10:30:30
viscircles([x0,y0],r);
hold  on
end

for j=1:n
Norm(j)=norm(Xk-[x(j),y(j)]);% calculate the distance from the initial point to all other points, 2-norm
Top(j)=W(j)*x(j)/Norm(j); % top of 2.5
Bottom(j)=W(j)/Norm(j);% bottom of 2.5
S(j)=W(j)/Norm(j); % 2.8
end

Tx=sum(Top)/sum(Bottom); % Eqn 2.5
SatBarx=(sum(S))^(-1);

count=0;

while (abs(NewX(1)-Xk(1))>0.0001 && abs(NewX(2)-Xk(2))>0.0001)
Xk=NewX;
for j=1:n
Norm(j)=norm(Xk-[x(j),y(j)]);
Top(j)=W(j)*x(j)/Norm(j);
Bottom(j)=W(j)/Norm(j);
S(j)=W(j)/Norm(j);
end
Tx=sum(Top)/sum(Bottom); % Eqn 2.5
SatBarx=(sum(S))^(-1);
count=count+1;
end
count+1
plot(NewX(1),NewX(2), 'r*')
for r=10:5:30
viscircles([NewX],r, 'LineStyle','--');
hold  on
end

``````

It’s not perfect, but there’s MATLAB to Julia translator | MATLAB to Julia converter

You can use PyPlot.jl, which wraps matplotlib, and you need some trivial changes.

2 Likes

What do you need help with specifically?

It’s unlikely that people will just blanket rewrite whole codebases for you, you’ve probably got a better chance if you make a start (maybe even by using an automated converter) and then asking specific questions if you can’t get something to work.

6 Likes

I recommend translating a line at a time from matlab to julia
and verifying that the result is correct. You may have to find
the corresponding packages and functions for the matlab ones.

1. See the julia documentation at https://docs.julialang.org/en/v1/ with special note to the “Noteworthy Differences from other Languages” and matlab

2. Start with the computations and loops first

3. Do plotting and visualization separate as that will depend on what features you need and what julia visualization package(s) you select

Good luck, have fun, and welcome to the Julia community!

2 Likes

Thank you very much. This sounds great. Am glad to join the Julia community.

This sounds great. Thank you

One thing that you will see is that Julia does not allow you to grow arrays/vectors in a for loop like you are doing in your Matlab code (e.g, writing Norm(j), Top(j)). This is a bad code practice in Matlab as well, but Julia will just error.

In Julia, you will have to pre-allocate (good) or use the function push! (not the best performancewise, but ok…).