How to plot Phasor in MATLAB - matlab

I have been working on Data Compression through SDT algorithm. I have been given a task to compress the data having 20001 points and I successfully compressed it into 944 points. Now I want to plot phasors in MATLAB. How to do it?
I used plot3 command but unfortunately could not get the desired result.
My code:
clear
clc
load('s.mat');
[N,~]=size(a(:,1));
b=[]
s=1; %storage point
a(s,6)=a(1,2); %vs, store the first phasor
a(s,5)=a(1,1); %ts
a(s,7)=a(1,3); %alphas
for n=3:1:N
p=n-1;
vp=a(p,2);
tp=a(p,1);
alphap=a(p,3);
vn=a(n,2);
tn=a(n,1);
alphan=a(n,3);
vs=a(s,6); %vs
ts=a(s,5);%ts
alphas=a(s,7);%alphas
for i=s+1:n-1 %Condtion for Vi and Current Points
ti=a(i,1);
alphai=a(i,3);
vi=a(i,2)*(cos(alphai)+1i*sin(alphai));%Phasors (Vi)
vcomp=((vn-vs)/(tn-ts))*(ti-ts)+vs;
alphacomp=((alphan-alphas)/(tn-ts))*(ti-ts)+alphas;
vcpx=vcomp*(cos(alphacomp)+1i*sin(alphacomp));%Phasors (Vcomp)
%Etve condition to convert ploar into rectangular components
e_TVE=norm((vcpx-vi),2)/norm(vi,2);%etve condition
a(i,4)=e_TVE;
if e_TVE<=0.001
continue;
else
s=p;
a(s,6)=vp; %vs
a(s,5)=tp;%ts
a(s,7)=alphap;%alps
% a(s,8)=a(p,6)*(cos(a(p,7))+1i*sin(a(p,7))); %Phasors of Storage point
break;
end
end
end
a(n,6)=vn; %vs,reserve the last data
a(n,5)=tn;%ts
a(n,7)=alphan;%alps
x=1;
for y=1:1:20001
if a(y,5)>0 || a(y,6)>0 || a(y,6)>0
b(x,1)=a(y,5);
b(x,2)=a(y,6);
b(x,3)=a(y,7);
x=x+1;
end
end
Figure 1 is the original (Uncompressed data):
Figure 2 is the compressed data result:
Figure 3 is the desired result:

Related

How to do an animate plot in MATLAB from a sequence of matrices

I have code that uses Wolff's Algorithm to simulate the XY Model in MATLAB and I want to implement a pcolor/color map to demonstrate each spin according to their angles across the system. But I want it to be live and changing as the angles change.
Any idea how to do this?
This is an example of how I want it to look https://i.stack.imgur.com/aSp7s.png
If you save each snapshot of the lattice in a cell array A{t}, you can use the following function to view and save it as a video (if fileName is not empty, the function saves an mp4 video).
Another option is to adapt the function view_lattice to run your simulation (which, honestly, I wouldn't recommend, for performance issues). I will mark where you should edit for doing a "live" simulation
This is at least MATLAB R2019b (although it may be compatible with earlier versions, but no guarantee).
File view_lattice.m
function view_lattice(A,fileName)
% for a 'live' simulation, you will have to remove A from the input
% parameters and add the ones you need for the XY Wolff algorithm,
% which will be used to calculate each configuration A in the time loop below
% you will also need to remove the assert statements for 'live' simulation
%
% otherwise, you save snapshots from your simulation
% and use this function as is
%
% A -> A{k}[m,n] snapshot k containing the angles of spins in lattice site at row m and col n
% fileName -> if contains string, then records a video with the snapshots and name it with this string
assert(iscell(A) && all(cellfun(#(a)isnumeric(a) && ismatrix(a),A)),'A must be cell of numeric matrices');
assert(ischar(fileName),'fileName must be either an empty char or contain a file name');
recordVideo = ~isempty(fileName);
if recordVideo
vw = setup_video(fileName);
else
vw = [];
end
% setting some default axis properties to speed-up plotting
set(0,'DefaultAxesPlotBoxAspectRatio',[1 1 1],'DefaultAxesDataAspectRatioMode','manual','DefaultAxesDataAspectRatio',[1,1,1],'DefaultAxesNextPlot','replace');
fh = figure;
ax=axes;
for t = 1:numel(A) % for 'live' simulation, this loop should be the time loop
% here you calculate the new configuration A
% and call the function below with A instead of A{t}
vw = record_frame(vw,fh,ax,A{t},t,recordVideo);
end
% any video to close?
if recordVideo
vw.close();
end
end
function vw = record_frame(vw,fh,ax,A,t,recordVideo)
imagesc(ax,A);
title(ax,sprintf('snapshot %g',t)); % if you want, y
axis(ax,'square');
daspect(ax,[1,1,1]);
pause(0.01);
if recordVideo
vframe = getframe(fh);
vw.writeVideo(vframe);
end
end
function vw = setup_video(fileName)
vid_id = num2str(rand,'%.16g');
vid_id = vid_id(3:6);
vid_id = [fileName,'_',vid_id];
% Initialize video
vw = VideoWriter([vid_id,'.mp4'], 'MPEG-4'); %open video file
vw.Quality = 100;
vw.FrameRate = 16;
vw.open();
end
Test script: test.m
clearvars
close all
A = cell(1,30);
for t = 1:numel(A)
% creating a sequence of random snapshots only for illustration
A{t} = rand(20,20);
end
% viewing the animation and saving it as a video with name test
view_lattice(A,'test');
Output

plotting trajectories using matlab

Im trying to plot trajectories on matlab
My data file (try.txt) that has the trajectories looks like this:
NumofTrajectories
TrajID1 #ofPoints x y x y....
TrajID2 #ofPoints x y x y....
example:
7
0 23 898.6 673.0 859.1 669.9 813.7 667.8 776.8 664.0 739.8 662.1 699.9 654.7 664.5 649.6 625.3 645.5 588.2 640.6 552.3 634.2 516.6 628.2 477.2 624.3 442.1 613.6 406.7 603.4 369.5 599.8 332.7 594.1 297.4 585.2 258.6 583.7 224.1 573.1 191.2 556.8 152.7 554.0 115.1 546.0 79.6 535.8
1 8 481.4 624.9 445.9 596.3 374.5 573.9 354.2 541.0 334.2 508.9 327.6 474.1 324.6 437.5 324.2 390.3
2 24 151.6 570.8 188.3 556.5 225.1 547.7 257.9 529.4 292.9 509.8 326.8 496.8 356.2 476.0 391.2 463.3 423.7 447.9 455.7 431.8 489.2 416.0 524.3 405.3 560.0 395.9 595.8 385.6 632.8 376.1 671.5 372.0 706.9 361.8 742.3 347.3 778.0 334.5 820.5 336.5 856.5 325.0 894.5 309.5 946.1 309.9 990.5 287.0
3 3 594.2 580.4 566.6 544.3 544.9 509.4
4 5 281.8 661.9 266.8 623.4 246.2 576.4 229.7 541.0 220.9 498.4
5 2 563.6 511.3 532.5 479.7
6 5 571.9 617.7 525.6 576.4 481.0 551.9 456.8 524.2 419.7 474.0
I'm trying to plot this on matlab
my code is as follows:
clc;
clear;
%read the input
importfile('try.txt')
%See how many trajectorys there are convert to number
nTraj=str2num(cell2mat(textdata));
%loop over the trajectories
for i = 1:nTraj
disp(data(i,1));
%print the current trajectory number of points
disp(data(i,2));
%get the x-y coordinates of each trajectory
current_traj=data(i,2);
for j=1:current_traj
points=data(i,3:j*2+2);
end
%print the x-y coordinates of each trajectory
%disp(points);
%seperate the x-y coordinates of each trajectory
x=points(1:2:length(points)-1)
y=points(2:2:length(points))
xlabel('latitude');
ylabel('longitude');
plot(x,y,'r');
grid on ;
hold on;
end
And function importfile:
function importfile(fileToRead1)
%IMPORTFILE(FILETOREAD1)
% Imports data from the specified file
% FILETOREAD1: file to read
DELIMITER = ' ';
HEADERLINES = 1;
% Import the file
newData1 = importdata(fileToRead1, DELIMITER, HEADERLINES);
% Create new variables in the base workspace from those fields.
vars = fieldnames(newData1);
for i = 1:length(vars)
assignin('base', vars{i}, newData1.(vars{i}));
end
The code sometimes works and usually gives me an error say:
Index exceeds matrix dimensions.
Error in ==> plotTrajectory at 23
points=data(i,3:j*2+2);
Can someone explain the error and tell me how to fix it?
The trajectories in try.txt have different lengths. importdata will use the first line to determine the length of your data. If another line is the longest, this line will be split over several lines of your imported matrix. At least this is what debugging shows. I would suggest you use another method to read your file. For me dlmread works:
%read the input
data = dlmread('try.txt', ' ');
% remove header
data = data(2:end,:);
%See how many trajectorys there are convert to number
nTraj=size(data,1);
You can replace your first lines with this code and remove your importfilefunction.

MSR Daily Activity 3D dataset matlab source code

I am searching for any matlab code that reads the skeleton text files from the dataset (MSR Daily Activity 3D). I can't figure how to understand how the files are written and what they represent ? Also, don't know how to parse them to extract the features.
this is the matlab code which read the depth sequences.
in each loop of 'for ei = 1:2',it read all the depth data to depth(a 3D matrix) from a bin file.
clear;close all;clc;
binPath = 'MSR Daily Activity 3D dataset\Depth';
for ai = 1:16
for si = 1:10
for ei = 1:2
%%%%%%%%%%%%%
%%%%%%%%%%%%%
[acsr,susr,exsr]=getsr(ai,si,ei);
%%%%%% getsr(ai,si,ei) convert ai,si,ei to double bits
%%%%%% for example, if ai=3, acsr is 03
%%%%%%%%%%%
binfile = [binPath,'\a',acsr,'_s',susr,'_e',exsr,'_depth.bin'];
if ~exist(binfile,'file');
disp('error');
continue;
end;
disp(binfile);
fileread = fopen(binfile);
if fileread<0
disp('no such file.');
return;
end
header = fread(fileread,3,'uint=>uint');
nnof = header(1); ncols = header(2); nrows = header(3);
depths = zeros(ncols, nrows, nnof);
for f = 1:nnof
frame = zeros( ncols, nrows);
for row = 1:nrows
tempRow = fread(fileread, ncols, 'uint=>uint');
tempRowID = fread(fileread, ncols, 'uint8');%%%%%
frame(:,row) = tempRow;
end
depth(:,:,f) = frame;
clear tempRow tempRowID;
end
fclose(fileread);
end
end
end
The site http://research.microsoft.com/en-us/um/people/zliu/ActionRecoRsrc/ tells you exactly how they're organised. They also provide some C++ example loaders.
"The format of the skeleton file is as follows. The first integer is the number of frames. The second integer is the number of joints which is always 20. For each frame, the first integer is the number of rows. This integer is 40 when there is exactly one skeleton being detected in this frame. It is zero when no skeleton is detected. It is 80 when two skeletons are detected (in that case which is rare, we simply use the first skeleton in our experiments). For most of the frames, the number of rows is 40. Each joint corresponds to two rows. The first row is its real world coordinates (x,y,z) and the second row is its screen coordinates plus depth (u, v, depth) where u and v are normalized to be within [0,1]. For each row, the integer at the end is supposed to be the confidence value, but it is not useful."
Hope this helps.

Vectorization of matlab code for faster execution

My code works in the following manner:
1.First, it obtains several images from the training set
2.After loading these images, we find the normalized faces,mean face and perform several calculation.
3.Next, we ask for the name of an image we want to recognize
4.We then project the input image into the eigenspace, and based on the difference from the eigenfaces we make a decision.
5.Depending on eigen weight vector for each input image we make clusters using kmeans command.
Source code i tried:
clear all
close all
clc
% number of images on your training set.
M=1200;
%Chosen std and mean.
%It can be any number that it is close to the std and mean of most of the images.
um=60;
ustd=32;
%read and show images(bmp);
S=[]; %img matrix
for i=1:M
str=strcat(int2str(i),'.jpg'); %concatenates two strings that form the name of the image
eval('img=imread(str);');
[irow icol d]=size(img); % get the number of rows (N1) and columns (N2)
temp=reshape(permute(img,[2,1,3]),[irow*icol,d]); %creates a (N1*N2)x1 matrix
S=[S temp]; %X is a N1*N2xM matrix after finishing the sequence
%this is our S
end
%Here we change the mean and std of all images. We normalize all images.
%This is done to reduce the error due to lighting conditions.
for i=1:size(S,2)
temp=double(S(:,i));
m=mean(temp);
st=std(temp);
S(:,i)=(temp-m)*ustd/st+um;
end
%show normalized images
for i=1:M
str=strcat(int2str(i),'.jpg');
img=reshape(S(:,i),icol,irow);
img=img';
end
%mean image;
m=mean(S,2); %obtains the mean of each row instead of each column
tmimg=uint8(m); %converts to unsigned 8-bit integer. Values range from 0 to 255
img=reshape(tmimg,icol,irow); %takes the N1*N2x1 vector and creates a N2xN1 matrix
img=img'; %creates a N1xN2 matrix by transposing the image.
% Change image for manipulation
dbx=[]; % A matrix
for i=1:M
temp=double(S(:,i));
dbx=[dbx temp];
end
%Covariance matrix C=A'A, L=AA'
A=dbx';
L=A*A';
% vv are the eigenvector for L
% dd are the eigenvalue for both L=dbx'*dbx and C=dbx*dbx';
[vv dd]=eig(L);
% Sort and eliminate those whose eigenvalue is zero
v=[];
d=[];
for i=1:size(vv,2)
if(dd(i,i)>1e-4)
v=[v vv(:,i)];
d=[d dd(i,i)];
end
end
%sort, will return an ascending sequence
[B index]=sort(d);
ind=zeros(size(index));
dtemp=zeros(size(index));
vtemp=zeros(size(v));
len=length(index);
for i=1:len
dtemp(i)=B(len+1-i);
ind(i)=len+1-index(i);
vtemp(:,ind(i))=v(:,i);
end
d=dtemp;
v=vtemp;
%Normalization of eigenvectors
for i=1:size(v,2) %access each column
kk=v(:,i);
temp=sqrt(sum(kk.^2));
v(:,i)=v(:,i)./temp;
end
%Eigenvectors of C matrix
u=[];
for i=1:size(v,2)
temp=sqrt(d(i));
u=[u (dbx*v(:,i))./temp];
end
%Normalization of eigenvectors
for i=1:size(u,2)
kk=u(:,i);
temp=sqrt(sum(kk.^2));
u(:,i)=u(:,i)./temp;
end
% show eigenfaces;
for i=1:size(u,2)
img=reshape(u(:,i),icol,irow);
img=img';
img=histeq(img,255);
end
% Find the weight of each face in the training set.
omega = [];
for h=1:size(dbx,2)
WW=[];
for i=1:size(u,2)
t = u(:,i)';
WeightOfImage = dot(t,dbx(:,h)');
WW = [WW; WeightOfImage];
end
omega = [omega WW];
end
% Acquire new image
% Note: the input image must have a bmp or jpg extension.
% It should have the same size as the ones in your training set.
% It should be placed on your desktop
ed_min=[];
srcFiles = dir('G:\newdatabase\*.jpg'); % the folder in which ur images exists
for b = 1 : length(srcFiles)
filename = strcat('G:\newdatabase\',srcFiles(b).name);
Imgdata = imread(filename);
InputImage=Imgdata;
InImage=reshape(permute((double(InputImage)),[2,1,3]),[irow*icol,1]);
temp=InImage;
me=mean(temp);
st=std(temp);
temp=(temp-me)*ustd/st+um;
NormImage = temp;
Difference = temp-m;
p = [];
aa=size(u,2);
for i = 1:aa
pare = dot(NormImage,u(:,i));
p = [p; pare];
end
InImWeight = [];
for i=1:size(u,2)
t = u(:,i)';
WeightOfInputImage = dot(t,Difference');
InImWeight = [InImWeight; WeightOfInputImage];
end
noe=numel(InImWeight);
% Find Euclidean distance
e=[];
for i=1:size(omega,2)
q = omega(:,i);
DiffWeight = InImWeight-q;
mag = norm(DiffWeight);
e = [e mag];
end
ed_min=[ed_min MinimumValue];
theta=6.0e+03;
%disp(e)
z(b,:)=InImWeight;
end
IDX = kmeans(z,5);
clustercount=accumarray(IDX, ones(size(IDX)));
disp(clustercount);
Running time for 100 images:Elapsed time is 103.947573 seconds.
QUESTIONS:
1.It is working fine for M=50(i.e Training set contains 50 images) but not for M=1200(i.e Training set contains 1200 images).It is not showing any error.There is no output.I waited for 10 min still there is no output.What is the problem?Where i was wrong?
To answer your second question, you can simply 'save' any generated variable as a .mat file in your working directory (Current folder) which can be accessed later. So in your code, if the 'training eigenfaces' is given by the variable 'u', you can use the following:
save('eigenface.mat','u')
This creates a .mat file with the name eigenface.mat which contains the variable 'u', the eigenfaces. Note that this variable is saved in your Current Folder.
In a later instance when you are trying out with your test data, you can simply 'load' this variable:
load('eigenface.mat')
This automatically loads 'u' into your workspace.
You can also save additional variables in the same .mat file if necessary
save('eigenface.mat','u','v'...)
The answer to the first question is that the code is simply not done running yet. Vectorizing the code (instead of using a for loop), as suggested in the comment section above can improve the speed significantly.
[EDIT]
Since the images are not very big, the code is not significantly slowed down by the first for loop. You can improve the performance of the rest of the code by vectorizing the code. Vectorized operations are faster than for-loops. This link might be useful in understanding vectorization:
http://www.mathworks.com/help/matlab/matlab_prog/vectorization.html
For example, the second for-loop can be replaced by the following vectorized form, as suggested in the comments
tempS = double(S);
meanS = mean(S,1);
stdS = std(S,0,1);
S = (tempS - meanS) ./ stdS;
Use MATLAB's timer functions tic and toc for finding how long the first for-loop alone is taking to execute. Add tic before the for loop and toc after it. If the time taken for 50 images is about 104 seconds, then it would be significantly more for 1200 images.

Create image from Huffman code - Matlab

I have a project about image compression in Matlab. So far i have successfully implemented Huffman encoding to the image which gives me a vector of binary codes. After that i run Huffman decoding and i get a vector which contains the elements of the image compressed. My problem is that i can find how is possible from this vector to reconstruct the image and create the image file.
Any help would be grateful
Update
Based on Ben A. help i have made progress but i still have some issues.
To be more exact. I have an image matrix. After finding unique symbols(elements) on this image matrix, i calculate the probabilities and then with this function:
function [h,L,H]=Huffman_code(p,opt)
% Huffman code generator gives a Huffman code matrix h,
% average codeword length L & entropy H
% for a source with probability vector p given as argin(1)
zero_one=['0'; '1'];
if nargin>1&&opt>0, zero_one=['1'; '0']; end
if abs(sum(p)-1)>1e-6
fprintf('\n The probabilities in p does not add up to 1!');
end
M=length(p); N=M-1; p=p(:); % Make p a column vector
h={zero_one(1),zero_one(2)};
if M>2
pp(:,1)=p;
for n=1:N
% To sort in descending order
[pp(1:M-n+1,n),o(1:M-n+1,n)]=sort(pp(1:M-n+1,n),1,'descend');
if n==1, ord0=o; end % Original descending order
if M-n>1, pp(1:M-n,n+1)=[pp(1:M-1-n,n); sum(pp(M-n:M-n+1,n))]; end
end
for n=N:-1:2
tmp=N-n+2; oi=o(1:tmp,n);
for i=1:tmp, h1{oi(i)}=h{i}; end
h=h1; h{tmp+1}=h{tmp};
h{tmp}=[h{tmp} zero_one(1)];
h{tmp+1}=[h{tmp+1} zero_one(2)];
end
for i=1:length(ord0), h1{ord0(i)}=h{i}; end
h=h1;
end
L=0;
for n=1:M, L=L+p(n)*length(h{n}); end % Average codeword length
H=-sum(p.*log2(p)); % Entropy by Eq.(9.1.4)
i calculate the huffman codes for the image.
Now i use this function:
function coded_seq=source_coding(src,symbols,codewords)
% Encode a data sequence src based on the given (symbols,codewords).
no_of_symbols=length(symbols); coded_seq=[];
if length(codewords)<no_of_symbols
error('The number of codewords must equal that of symbols');
end
for n=1:length(src)
found=0;
for i=1:no_of_symbols
if src(n)==symbols(i), tmp=codewords{i}; found=1; break; end
end
if found==0, tmp='?'; end
coded_seq=[coded_seq tmp];
end
where in src i put my image (matrix) and i get a coded sequence for my image.
Last is this function:
function decoded_seq=source_decoding(coded_seq,h,symbols)
% Decode a coded_seq based on the given (codewords,symbols).
M=length(h); decoded_seq=[];
while ~isempty(coded_seq)
lcs= length(coded_seq); found=0;
for m=1:M
codeword= h{m};
lc= length(codeword);
if lcs>=lc&codeword==coded_seq(1:lc)
symbol=symbols(m); found=1; break;
end
if found==0, symbol='?'; end
end
decoded_seq=[decoded_seq symbol];
coded_seq=coded_seq(lc+1:end);
end
Which is used to decode the coded sequence. The problem is that finally as coded sequence i get a 1x400 matrix where i should get a 225x400 which is my image dimensions.
Am i missing something? Maybe should i replace something because i have a matrix and not a number sequence (for which the code is written)?
You might want to take a look at this:
http://www.mathworks.com/matlabcentral/answers/2158-huffman-coding-and-decoding-for-image-jpeg-bmp
This seems like it's right up your alley. It should ultimately lead you to here:
http://www.mathworks.com/matlabcentral/fileexchange/26384-ppt-for-chapter-9-of-matlabsimulink-for-digital-communication