Implementing vectors to a matrix with Matlab coding - matlab

Hey I am using a FIR filter on a signal. And I want to make the HF variable a matrix that contains the values of L in the variable hf. Like this:
HF = [hf1, hf2, hf3, hf4, hf5];
So that I can use the matrix HF in a subplot there I can get a view over the plots of each hf vector.
As you can see I got a tip of writing HF = [HF, hf];that should implement the vector of hf to the matrix HF. But I can't get it to work.
Here is the code that I am using:
w0 = 9*pi/80;
for L = [5,10,50,100,1000]
n = 1:L;
dum = (sin(w0.*n))./(pi.*n);
h = [fliplr(dum),w0/pi,dum];
% stem(h);
hfft = fft([h,zeros(1,(4096-length(h)))]);
hf = log10(hfft.*conj(hfft)/(Fs*7)/2);
HF = [HF,hf];
%figure(7)
%plot(hf(1:2048));
%pause
end
r = 3;
c = 2;
Plotnb = 1;
for i=1:r
for j=1:c
subplot(r,c,Plotnb)
plot(HF(:,Plotnb)); % Picks out the right column.
Plotnb=Plotnb+1;
end
end
% y2=conv(x,h);
% sound(y2,Fs);
Any tips would be much appreciated!
Thanks for the help
Daniel

Almost there, you just need to add
HF = [];
before entering the for loop. If you don't do that, the program fails on HF = [HF,hf]; because you are trying to concatenate hf with something that does not exist yet.

Related

Integrate over a meshgrid space

Currently I'm working on a project trying to recreate Young's original experiment. To make a long story short, I have a rather complicated surface defined using matlab's meshgrid and I want to evaluate my defined function (fun in the code) over this surface.
My code is currently looking like this:
clc;
clear all ;
M = 20 ;
N = 100 ;
R1 = 1 ; % yttre radien
nR = linspace(0,R1,M) ;
nT = linspace(0,2*pi,N) ;
nx = linspace(-0.1,0.9,N);
ny = linspace(-1,1,M);
%nT = pi/180*(0:NT:theta) ;
[B, Z] = meshgrid(nx,ny);
[R, T] = meshgrid(nR,nT) ;
lambda = 1;
fun= #(s) e^((i*2*pi/lambda)*(1/2 * (cos(lambda/(4*pi*s))/2)));
% Convert grid to cartesian coordintes
X = R.*cos(T);
Y = R.*sin(T);
[m,n]=size(X);
% Plot grid
figure
set(gcf,'color','w') ;
axis equal
axis off
box on
hold on
for i=1:m
plot(X(i,:),Y(i,:),'k','linewidth',1.5);
end
for j=1:n
plot(X(:,j),Y(:,j),'k','linewidth',1.5);
plot(B(:,j),Z(:,j),'b','linewidth',1.5);
end
If you try to run my code, I want to evalute the function fun over all the space in the meshgrid except for the blue part, can this be done or should I restart and approach the problem in a different way? Thanks in advance

How to plot a matlab function for different parameters using hold on command

I have a matlab function that contain some constant parameter, I want to draw that function, on say same figure, using hold on (probably) while changing the value of that constant.
This my code:
close all
clear all
clc
m = 5;
x = 1:1:10;
y = m*x + 10;
h1 = figure;
plot(x,y)
m = 10;
figure(h1);
hold on
plot(x,y,': r')
When I tried using this code, I got two lines coincident on each others; and it looks matlab just used last value for the parameter m how can I make it use different values.
I found some stuff here, but doesn't fulfill my needs.
Any suggestions?
You need to recalculate y as well:
m = 5;
x = 1:1:10;
y = m*x + 10;
h1 = figure;
plot(x,y); hold on;
m = 10;
y = m*x + 10;
figure(h1);
plot(x,y,': r')
Or create an anonymous function:
x = 1:1:10;
f = #(m) m*x + 10;
%// and then:
h1 = figure;
plot(x,f(5) ); hold on;
plot(x,f(10),': r');
Currently, you're only updating m but you also have to calculate y again. This is why it plots exactly the same y (i.e. m is still 5) function when you issue the second plot.
You might want to use a simple for loop for that, like:
m = 5;
x = 1:1:10;
figure;
hold on;
for m=1:1:10
y = m*x + 10;
plot(x,y,': r')
end
In addition to the short answer - improving the plot..
%% Data Preparations
x = 1:10;
ms = 3; % number of different slopes
%% Graph Preparations
hold on;
% Prepare the string cell array
s = cell(1, ms);
% Handle storage
h = zeros(1, ms);
% Plot graphs
for m=1:ms
y = m*x + 10;
h(m)= plot(x,y,'Color',[1/m rand() rand()]);
s{m} = sprintf('Plot of y(m=%d)', m);
end
% Plot all or select the plots to include in the legend
ind = [ms:-1:1] .* ones(1,ms); % plot all
%ind = [ 1 3 4 ]; % plot selected
% Create legend for the selected plots
legend(h(ind), s{ind});
Additional advice: When working with MATLAB and you try to improve the performance of your code, you shoud try to avoid using for-loops since MATLAB is MATrix manipulation and that's what it can do best. Ones you've taken this philosophy in, you'll create the most beautiful code one-liners! ;)
This script is an adoption of Steve Lord's post.

finding the sum of elements in a row and putting them in a column vector

M = round(csvread('noob.csv'))
save projectDAT.dat M -ascii
load projectDAT.dat
mat = (projectDAT)
rowws(mat)
This is my main script. I have a excel file, which opens up a 20 x 20 matrix in matlab. Now I have to call a function in this mainscript, which would find the sum of elements in a row for me and put them in a column vector. Here is my function:
function sumRow = sum_of_rows(mat)
[m n] = size(mat);
sumRow = zeros(m,1);
for i = 1:m;
for j = 1:n;
sumRow(i) = sumRow(i) + mat(i,j);
end
end
vec = sumRow;
end
I am required to plot a line graph using this column vector. I am supposed to call a function from the mainscript. The function should be able to take the input from this sum_of_rows function. I tried doing this:
function plotthegraph(~)
% Application for plotting the height of students
choice = menu('Choose the type of graph', 'Plot the data using a line plot', 'Plot the data using a bar plot');
if choice == 1
plot_line(sum_of_rows)
y = sum_of_rows
x = 1:length(y)
plot(x,y)
title('Bar graph')
xlabel('Number of characters')
ylabel('Number of grades')
elseif choice == 2
plot_bar(sum_of_columns)
end
Its not working out though. Can someone please help me out, I would really appreciate it.
Thank you.
Have you considered using the builtin sum function? I think
mysum = sum(mat,2)
would do the trick.

Matlab plot in loop error

I am creating figures in a for loop. The figure is a 2D mesh plot, which is supposed to be updated every iteration. The value to be plotted in a 200x200 array.
My problem is: It seems the calculation is running every iteration, but the plot is always the first one created, no matter I just plot or save to file.
Here is my code:
x = 1:200;
y = x;
for i = 1:100000
c = calculate(stuff, c); % value to be created, nothing to do with x and y
h = figure;
mesh(x,y,c);
saveas(h, sprintf('FIG%d.jpg',i);
drawnow; % did not work with or without this command
close(h);
end
First, thank you for all your inputs and suggestions! I didn't expect to get so many help within such a short time!
Then, I can answer some of the confusions here.
To Daniel: yes the c is changing. The program is calculating c based on its previous value. And there is sufficient step for c to change.
To R.Schifini: I tried pause(.1) but it didn't help unfortunately
To Andrew: thanks for pointing it. The complete program is attached now. And as to Daniel, the program calculate the value of c based on its previous values.
To The-Duck: I tried clf(h, 'reset') but unfortunately it didn't help.
Complete code:
Main program: please refer to wikipedia for the physical equation if you are interested
http://en.wikipedia.org/wiki/Cahn%E2%80%93Hilliard_equation
% Program to calculate composition evolution for nucleation and growth
% by solving Cahn-Hilliard equation - Time dependent non-linear
% differential equation
% Parameter
sig = 0.1; % J/m^2
delta = 10E-9; % m
D = 1E-9; %m^2/s
A = 10*sig/delta; % J/m
K = 3*sig*delta; % J/m^3
M = D/(2*A); % m^2/s
N = 200; % mesh size
dt = 1E-12; %s
h = delta/10;
% Rng control
r = -1+2.*rand(N);
beta = 1E-3;
n = 10000;
% initialization
c0 = zeros(200);
c0 = c0+ 0.1+beta.*r;
c = c0;
x = h.*linspace(-N/2,N/2,N);
y=x;
% Iteration
for i = 1:n
LP_c = laplacian(c,h);
d_f = A*(4*(c.^3)-6*(c.^2)+2*c);
sub = d_f - (2*K)*LP_c;
LP_RHS = laplacian(sub,h);
RHS = M*LP_RHS;
c = c + dt.*RHS;
% Save image every 2000 steps
% if ( i==1000 || i==10000 || i==100000)
% h = mesh(x,y,c);
% pause(.1);
% saveas(h, sprintf('FIG%d.jpg',i));
% clf(h,'reset');
% end
end
%h = figure;
mesh(x,y,c);
Laplacian function:
function LP_c = laplacian(c,h)
v1 = circshift(c,[0 -1]);
v2 = circshift(c,[0 1]);
v3 = circshift(c,[-1 0]);
v4 = circshift(c,[1 0]);
LP_c = (v1+v2+v3+v4-4.*c)./(h^2);
end
Result:
You can see the commented part in main program is for plotting periodically. They all give the same plots for each iteration. I tried the current OR version, also tried if ( mod(i,2000) == 0) to plot more pics. There is no difference. Shown:
However, if I comment out the periodic plotting, just run the program for different values of n, I got different plots, and they obey physical laws (evolving structure), shown in time order
Therefore I excluded the possibility that c might not update itself. It has to be some misuse of the plotting function of matlab. Or maybe some memory issue?
An interesting point I discovered during edition session: If I put the command h = figure in front of the loop and plot after the loop end, like this:
h = figure;
% Iteration
for i = 1:n
LP_c = laplacian(c,h);
d_f = A*(4*(c.^3)-6*(c.^2)+2*c);
sub = d_f - (2*K)*LP_c;
LP_RHS = laplacian(sub,h);
RHS = M*LP_RHS;
c = c + dt.*RHS;
end
mesh(x,y,c);
It seems all value of c calculated during the loop will overlap and give a figure shown below: I guess this indicates some facts about the plotting function of matlab, but I am not sure
Btw, can I answer directly to each comment and high light the new added section in my post? Sorry I am not as familiar with Stack Overlow as I should have :)
I ran your routine and with the following changes it works for me:
% Iteration
for i = 1:n
LP_c = laplacian(c,h);
d_f = A*(4*(c.^3)-6*(c.^2)+2*c);
sub = d_f - (2*K)*LP_c;
LP_RHS = laplacian(sub,h);
RHS = M*LP_RHS;
c = c + dt.*RHS;
% Save image every 2000 steps
if ( mod(i,2000)==0)
h1 = mesh(x,y,c);
drawnow;
saveas(h1, sprintf('FIG%d.jpg',i));
end
end
The main change is the figure handle variable from h to h1. Why? You are already using variable h in your equations.
Regards,

Matlab smooth a 3d mesh plot

Hi I have a set of data A with each element corresponding to an x and y combination. When I plot this dat using mesh I get a graph with many spikes on it. This is not unnexpected but I would like a way to smooth these out to get a smooth surface.
I've tried to use the smooth3 command but cannot figure out how to make the suitable input.
Any help would be appreciated. Thanks
This is how my data is generated.
function v = f(x,y) % Not actual function
return x*rand()+y*rand()
end
x = 0.05:0.01:0.95;
y = 0.05:0.01:0.95;
o = zeros(length(x),length(y));
A = zeros(length(x), length(y));
for k = 1:5
for i = 1:length(x)
for j = 1:length(y)
o(i,j) = f([x(i), y(j)]);
end
end
A= A+o;
end
A = A/5;
This is what produces the plot.
[X,Y] = meshgrid(x);
mesh(A)
my be you can try a convolution of your variable A with a filter(the following is an example of a Gaussian filter).
C = conv2(A,fspecial('gaussian', hsize, sigma));
check conv2 and fspecial in matlab help