I have been programming a lot in matlab recently. However, I was not told about some of the cool tricks in class.
For a beginner, getting interactive user input and how to generate plot and save it would be interesting.
so here is an example. just enter a number ‘b’ and we will generate a vector y, that is b random numbers between -10 and 10 and plot it by using x = 1,2,3,…,b and y = y1, y2, y3,…,yb. and plot it and save the picture.
%% this scripts shows how to get user input
clear all % to clear everything in the work space % to avoid that a variable already exist in our workspace
%enter b
b = input(‘enter b: ‘); %generate b random integer between -10 and 10.
y = randi([-10,10],1,b);
Soon it will be my 4th year as a licensed skydiver. Something i will always practice is my emergency procedure. For those who is not familiar with emergencies, below is a video:
We train on this all the time, but I still have not got my first cut away yet. With my gear, I am playing extra safe, once the wind picks up, there is the famous saying “Better to be on the ground wishing you were in the air than being in the air and wishing you were on the ground.”
I still do not have the courage to write about what exactly happened on my 28th birthday. (an incident that my bags were stolen at the rental car at barcelona airport, i was left with nothing but a phone in my hand.)
While remembering the details is somewhat a bit painful for me, but i thought writing down the emergency procedures could be helpful.
1. call credit cards to report lost card!!!
This is definitely a must, and should be done ASAP. My passport, license, ID cards were all lost together with my American express and HSBC credit cards. Unlike the majority of Europe that you use a 4 digit pin code for transactions. Hong Kong issued credit cards use signature to finish the transaction. While sweden is the only place that they check ID when I used my card. But with ID and card together, you never know what will happen. Luckily i discovered that my things were gone, even with the hope that “maybe i could find it back…”( with the probability is the same as you will end up marry your high school boyfriend) 99% of my heart know that they are gone forever.
I definitely need to praise the excellent customer service from american express, they helped everything very fast, an emergency replacement card were sent to my oversea address just the day. But I was not very lucky with DHL delivery, I received my AMEX card in a week.
Sadly, the classic HSBC credit card with red strip on the silver background is gone forever, it was my first credit card from first year of university. HSBC has new card design.
2. Police report
It’s a must for insurance claim, and assuming everyone now has travel insurance… so get a report.
3. get temp passports
thanks hong kong immigration 24 hr hotline. call +8521868
after a desperate experience, hk immigration did tell me all i need to do to get temp travel document, either to the next destination, or go back immediately. so everything started to work after that.
4. Survive without any cash or card
I was extremely lucky that i found friends who reached out a hand for me and gave me shelter and money for that weekend. otherwise i would not know what to do.
5. The endless long waiting for getting new passport, ID and licenses.. queueing, talking to immigration officer, explain what happened. long line at Transport department to get a replacement license… and still in the procedure of getting my danish license transferred to a Swedish one.
I had the best birthday 13 years ago, and now the worst one.
13 years ago, a boy gave me a box of chocolate in the shape of heart and we said what we wanted each other to say. We were really good friends, and even though it did not last long. It was the best in my life, and there is always a piece of my heart that saves the memory of us in those young days.
This year, I have my bags stolen from a rental car en route to empuriabrava for a weekend skydiving and tunnel flying fun. And in the two bags that were stolen, there were all my cash, cards, passport,macbook air with all my homework and lots of other programs, id, licenses, clothes, food, shoes, etc… Everything I had for that trip. I only had the phone not stolen because i had them in my hand. It was terrible. I am still trying to dealing with everything afterwards, getting new id, replace the cards… As of now life is still difficult, I did all i could do, now it’s the long process to bring life back to normal.
Around Christmas 2017, there were continuous dreams about that boy in my sleep. 3 nights in a row, there he was, in my dream. The last time, he appeared in my dream was in 2016. And something very bad happened. But this year, stolen bags at barcelona airport was worse than that.
Am I hitting the absolute bottom this year? with the crazy land lady turning off the heating and hot water just 1 day before i leave, not doing so well in the FEM exam, and getting all stolen at airport? and my dear grandmother passed away two days ago. It was a lot to take at the moment. But does it mean that it was an end of something?
In the world where I assumed every one is self interested agent, many people reached out a hand to help me. I’ll remember your kindness. and I will try to do the same to others who needed any help.
end of this era. I’ll try to live a better life. Aren’t we skydivers all well prepared for the emergency?
I went back to Hong Kong in the beginning of this month. and I took this picture on the foot bridge at the entrance to western harbor crossing from Kowloon Side.
All i have say is, this phone is awesome. First one is with iPhone x and the second one is with my old iphone 6. Standing at the same place, those two phones told a different story.
This was exactly the moment I wanted to quote “Different people remember things differently, and you’ll not get any two people to remember anything the same, whether they were there or not. You stand two of you lot next to each other, and you could be continents away for all it means anything.” by Neil Gaiman.
People everywhere told me, the new iPhone is too expensive. But the face ID, animoji, awesome camera. Is it worth it? Purely my opinion, yes, I paid almost 10k for this phone and i think it’s a good spending of money.
I thought the face ID would be bad as touch ID, which i rarely use. But the face ID is great. the first two days, it was struggling, but soon its learning algorithm started to capture my face feature, and by the time I was sitting on my favorite Emirates flight back to Sweden, it worked without me having to take my sun glasses off. That was the moment of true”WOW”.
Another cool thing is the new feature from photo. I have to admit that I never upgrade IOS because of what happened from IOS6 to IOS7 about the appearance of default apps. This “best of 2017” was a huge surprise. It captured every single moment that was in my trip back to Hong Kong. it felt very personal and with the music (quite some strong Chinese element inside) and perfectly cropped the long video of the whole take off from Dubai. I would not be able to make such a good video. It told a perfect story.
Is deep learning the next big thing? I have had friends sharing on instagram about this “best of ” video series and seems quite a lot very positive feedback. Now i am seriously interested in deep learning algorithms with neural networks. Perhaps, that is the way to lead us finding our individual utility function, and with some tracking inputs from user, it can eventually predict the marginal utility.
That would be seriously cool, and open the door of wants = needs.
Recently I used power methods for getting the largest eigenvalue and the corresponding eigen vector in both matlab and python.
It is obvious, matlab is the easy way for matrix operation. as python is using array of list, so a little complicated if you written your own matrix multiply operation function. And it’s much slower using your own function, but it surely was a way to practice how you think, and make sure you are doing right with all the i, j,k indices.
Here is what I wrote in Matlab: The converge rate of the power method depends on λ2/λ1, (here λ2 is the 2nd largest eigenvalue and λ1 is the largest eigenvalue). It can take some iterations:
Example is from classical oscillation, we could find the eigenfrequency and visualize the eigenvector as how it vibrates. and here is the code:
in order for it to converge fast, I added Rayleigh quotient after some number of power method iteration. you should change it according to your need. When matrix size is not big and the required accuracy is not high, power methods general gives out stable and good results. Integrate Rayleigh in the algorithm could save us some iteration times, but then it might not be stable and require multiple trials or have a relatively large power iteration first. Computing inv(A- λ *I) is relatively expensive and when high accuracy of eigenvalue is required, (A- λ *I) will be nearly singular as Ax=λx , this could also cause trouble. but in general, it works great!
n=input('please enter n:');
h=1/n;
a=2*ones(1,n);
a(n)=1;
b=ones(1,n-1);
K=diag(a)-diag(b,1)-diag(b,-1);
M=2*diag(a)+diag(b,1)+diag(b,-1);
K=(1/h)*K;
M=(h/6)*M;
A=inv(M)*K;
c=ones(n,1);
z=c;
i=0;
r=1;
I=eye(n);
error=1;
for j=1:5000
z=A*z;
z=z/norm(z);
end
while abs(error)>1e-4
r=(z'*A*z)/(z'*z);
z=inv(A-r*I)*z;
z=z/norm(z);
i=i+1;
newr=(z'*A*z)/(z'*z);
error=newr-r;
end
r
disp([num2str(i),' iteration'])
abc=eig(A);
abc(1)
plot(z)
Next, we can use python and with numpy library help us do some maths.
It requires more coding, and structure, it’s simply on paper, a few lines and then power method are there. but telling the computer to get the right thing done is slightly more expensive. But I wrote two different methods, one basicly used a function to compute matrix multiplication and calculate vector 2-norm. another calling some useful numpy command as
numpy.linalg.norm
numpy.linalg.eig
numpy.dot
Below is an example for doing it in python, it might not be the best way, but it’s very detailed structured. and a lot of basic command is included.
#this is compute the largest eigenvalue and corresponding eigenvector using power method for matrix A
#written by Peili Guo (contact@guopeili.com)
import numpy as np
import timeit # for timing code snippets
import math # for math functions
#------------------------------------------function below-------------------------------------------------
def mm_multi(A,B):
'''compute AxB
#example A=[[1,2],[3,4]] and B=[1,1], will return [3,7]
#Input A matrix, B vector'''
C=[[0 for x in range(len(B[0]))] for y in range(len(A))]
if (len(A[0])==len(B)):
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k] * B[k][j]
return C
else:
return "goodbye"
#------------------------------------------function above-------------------------------------------------
#-----------------------------------i am powerful dash line-----------------------------------------------
#------------------------------------------function below-------------------------------------------------
def twonorm(a):
'''compute 2 norm of a given vector,
#example a=[1,1], will return 1.414
#Input a is vector'''
sum=0.0
for i in range(len(a)):
for j in range(len(a[0])):
sum+=a[i][j]*a[i][j]
return((math.sqrt(sum)))
#------------------------------------------function above-------------------------------------------------
#-----------------------------------i am powerful dash line-----------------------------------------------
#------------------------------------------function below-------------------------------------------------
def findev(M,tol,totalrun):
'''here we will find the eigenvector corresponding to the largest eigenvlue of a given matrix, magic?
using power method, you can do it, by iterate it again and again and again
until the error margin is satisfied
input M is a matrix, and tol is your error margin, and the total max iteration inside the while loop
Input a can be vector or matrix'''
i=0
N=len(M[0])
#print('N',N)
zold = np.random.random((N,1))
#print('zold',zold)
err=10
znew = np.random.random((N,1))
#print('znew',znew)
#print('znew[0]',znew[0][0])
#print('znew[0]',znew[1][0])
while (err>tol):
znew = mm_multi(M,zold)
zmax=np.max(znew)
znew = znew/zmax
err = twonorm(znew-zold)
zold=znew
i=i+1
if i > totalrun:
break
if i > totalrun:
return "goodbye"
else:
return(znew)
#------------------------------------------function above-------------------------------------------------
#-----------------------------------i am powerful dash line-----------------------------------------------
#------------------------------------------function below-------------------------------------------------
def findeveasy(M,tol,totalrun):
'''here we will find the eigenvector corresponding to the largest eigenvlue of a given matrix, magic?
using power method, you can do it, by iterate it again and again and again
until the error margin is satisfied
input M is a matrix, and tol is your error margin, and the total max iteration inside the while loop
Input a can be vector or matrix'''
i=0
N=len(M[0])
#print('N',N)
zold = np.random.random((N,1))
#print('zold',zold)
err=10
znew = np.random.random((N,1))
#print('znew',znew)
#print('znew[0]',znew[0][0])
#print('znew[0]',znew[1][0])
while (err>tol):
znew = np.dot(M,zold)
zmax=np.max(znew)
znew = znew/zmax
err = np.linalg.norm(znew-zold)
zold=znew
i=i+1
if i > totalrun:
break
if i > totalrun:
return "goodbye"
else:
return(znew)
#------------------------------------------function above-------------------------------------------------
#here we start by initial yourmatrix and z0 for iteration
#define size
totalrun=1000 #you can change this totalrun number as you like, but it might be slow, if your N is small
N= input('what size is your matrix? ')
#create a random matrix, and you can also input your marix, let yourmatrix = the matrix you want to compute
yourmatrix=np.random.random((N,N))
#error tolerance
errtol = 10**(-6)
####################use method 1###########################################################################
#we call method number 1 to find largest eigenvector and eigenvalue and time the whole process
#in this method 1, a lot of computing is using function written above
start_time = timeit.default_timer()
# call the function findev
ourev=findev(yourmatrix,errtol,totalrun)
#get the eigenvector now compute eigen value
#we compute lamda, using basic multiplication that lamda=transpose(y)*A*y/transpose(y)*y
znewtran=np.zeros((1,N))
for i in range(len(ourev)):
znewtran[0][i]=ourev[i][0]
Ay=mm_multi(znewtran,yourmatrix)
ytAy=mm_multi(Ay,ourev)
yty=mm_multi(znewtran,ourev)
l1=ytAy[0][0]/yty[0][0]
time1 = timeit.default_timer() - start_time
#print('elapsed time in compute_reciprocals(): %1.5f' % time1)
####################use method 2###########################################################################
#we call method number 2 to find largest eigenvector and eigenvalue and time the whole process
#in this method, most numpy package is used for computing and we will compare the speed!
start_time = timeit.default_timer()
# call the function findeveasy
ev2=findeveasy(yourmatrix,errtol,totalrun)
#get the eigenvector now compute eigen value
#we compute lamda, using basic multiplication that lamda=transpose(y)*A*y/transpose(y)*y
ev2t=np.transpose(ev2)
l2=np.dot(np.dot(ev2t,yourmatrix),ev2)
l2=l2/np.dot(ev2t,ev2)
time2 = timeit.default_timer() - start_time
#print('elapsed time in compute_reciprocals(): %1.5f' % time1)
####################finish computing below are output######################################################
print('eigenvector by method 1',ourev)
print('eigevalue by method 1',"%.6f" % l1)
print('computing time for method 1: %.6f' % time1)
#format with 6 decimal output
print('eigenvector by method 2',ev2)
print('eigevalue by method 2',"%.6f" % l2)
print('computing time for method 2: %.6f' % time2)
#format with 6 decimal output
evals,evecs=np.linalg.eig(yourmatrix)
ltrue=max(evals.real)
print('eigevalue by np.linalg.eig ',"%.6f" % ltrue )
#format with 6 decimal output