Plotting measured data along with Bode plot - matlab

I am taking a circuits class and for lab we need to do a little work with MATLAB to plot some of the results. I got the following code which I used to generate a Bode plot of the transfer function for a filter we were designing. I sort of get how it works but I don't really know or use MATLAB outside of this class.
clc;
close all
s=tf('s');
w=628*1000;
H=(1/(1 + 1.85*s/w + s^2/w^2))*(1/(1 + 0.77*s/w + s^2/w^2));
figure;
bode(H)
This worked fine but now I need to plot the transfer function I measured in the lab against this data on the SAME plot axis. How can I plot both of them together. I have the lab data as a list of gain frequency pairs.

Instead of bode(H), try:
[mag,ph,w] = bode(H); % gets the data without generating the figure
plot(w, mag, 'b'); % plots only the magnitudes
freqs = data(:,1); % These 2 lines depend on how your data is formatted
gains = data(:,2); % These 2 lines depend on how your data is formatted
hold on % will add new content to the existing figure without erasing the previous content
plot(freqs, gains, 'r');
hold off
you could also try (inspired by http://www.mathworks.com/help/ident/ref/bodeplot.html) :
h = bodeplot(H);
setoptions(h,'FreqUnits','Hz','PhaseVisible','off'); % suppress the phase plot
freqs = data(:,1); % These 2 lines depend on how your data is formatted
gains = data(:,2); % These 2 lines depend on how your data is formatted
hold on % will add new content to the existing figure without erasing the previous content
plot(freqs, gains, 'r');
hold off

Related

Looping over subplots and holding [duplicate]

This question already exists:
Matlab subplots in loop: only shows plots in last iteration
Closed 3 years ago.
I'm trying to create a plot and layer multiple functions over each of the subplots. The output I'm getting, however, is only showing the final plot in each iteration. In other words, all subplots are filled with something, but only with the last curve that I 'added' (or at least I thought I did) -- the cyan curve. I tried using hold onin a number of different places, to no avail. Does anyone see what the problem might be?
%% Training phase
% Setting for plots
figure;
for tai = 1:length(training_algorithms)
% Create first subplot (and make sure we stay there)
subplot(3,2,tai);
% Plot the (sampled) sine function
plot(x,y,'bx');
hold on
colors = ['r', 'm', 'c'];
for nh = 1:length(num_hid)
net = networks{tai, nh}; % Load network
net.trainParam.showWindow = false; % Don't show graph
% Train network, and time training
tic;
[net, tr] = train(net, p, t);
durations(tai)=toc;
% Simulate input on trained networks (and convert to double format)
y_result = cell2mat(sim(net, p));
% Evaluate result
[slo, int, correlations{tai}] = postregm(y_result, y);
% Add network to array
networks{tai} = net;
% Plot network approximation results
plot(x,y_result,colors(nh))
ylim([-3 3])
title(training_algorithms{tai});
end
hold off
end
It looks like this has been answered already but it is also worth noting that even though you are setting the net.trainParam.showWindow property to 'false,' Matlab may still create a new figure and make it active even though it remains hidden. Then any plots you perform after that won't stack like you want unless you make the original plot active again.
For example, if you run the below code (I stripped out all of your specific functions but recreated the affect) you will see that at the end, there are 20 or so figures open but only 1 is visible. Uncommment the line towards the bottom in order to create the kind of stacked subplots you are after... Hope this helps.
Cheers.
% Training phase
% Setting for plots
f1=figure(1);
for i = 1:6
% Create first subplot (and make sure we stay there)
subplot(3,2,i);
x=0:.1:2*pi;
y=sin(x);
% Plot the (sampled) sine function
plot(x,y,'b');
hold on
colors = {'r', 'm', 'c'};
for j=1:3
f2=figure;
set(f2,'Visible','off');
y2=sin(x+j);
% Plot network approximation results
% figure(f1) % - uncommment me
plot(x,y2,colors{j})
end
hold off
end
figHandles = findobj('Type', 'figure')

Calclulating a set of lines slopes after using Xlim in Matlab

I'm plotting a series of lines in MATLAB and the figure is like this:
As you can see the X-axis is Frequency, I want to limit the frequency spectrum so I use Xlim function in my code to select my desired bandwidth while plotting.
Now I want to calculate the slope of those lines in the chosen frequency bandwidth (what's in the plot window), not the entire band but if I choose the basic fitting option, it's clearly giving me a linear fit for the line over the entire frequency band.
Any advice?
Thanks.
You can do this in the matlab script:
% your data
f = linspace(2e7,11e7,100);
x = linspace(-0.5,-2.5,100)+0.1*rand(1,100);
% Linear fit in a specific range:
[~,i] = find( f>3e7 & f<9e7 ); % <= set your range here
p = polyfit(f(i),x(i),1); % <= note the (i) for both variables
figure;
hold all
plot(f,x,'r.-')
plot(f(i),polyval(p,f(i)),'k-','LineWidth',2) % <= polyval takes the 'p' from polyfit + the data on the x-axis
% the fit is y = p(1)*x+p(2)
You won't be able to use the basic fitting GUI for what you want to do. You will probably need to write a custom function that will "crop" the data in question to the x-limits of your current view. Then use polyfit or similar on those data segments to create the fit.

Matlab: Loop over files, plot data in one figure & add file names as legend

I have a folder with several files, each of them containing some hundreds of data pairs (resistance R over Temperature T). The files do not contain the same amount of data points...
I want Matlab to read in the files, loop over them and plot R(T) of every single file, but all in one figure. Moreover, I want the file names as legends for the different graphs (eg, the plot resulting form file 'Example1.dat' should be indicated as 'Example1.dat' in the legend).
What I am doing right now is the following:
files=dir('*.dat') % Get all input files
hold on % multiple plots in one figure
for file=files' % loop over files
[T, R] = textread(file.name,'%f %f') %get data points
xlim([8.5 10]) % set limits
ylim([-0.5 2.5]) % set limits
plot(T,R) % plot
end
legend(files.name) % add legend
What I get does not look right, because every time I try it, the same graph gets a different name in the legend. How can I fix it?
try this
files=dir('*.dat') % Get all input files
hold on % multiple plots in one figure
for filenumber=1:length(files) % loop over files
[T, R] = textread(files(filenumber).name,'%f %f') %get data points
plot(T,R) % plot
end
%limits only need to be fixed at the end
xlim([8.5 10]) % set limits
ylim([-0.5 2.5]) % set limits
legend(files.name) % add legend

How to switch between subplots of different figures inside a for loop in MATLAB

Consider the following code snippet,
%% Declare figures
figure(1); % Plot Measured (y) Vs Reference(x) data for 6 cases
figure(2); % Plot Regression fit for Measured vs Reference for 6 cases
%% Run algorithm for 6 cases
for i=1:6
:
:
subplot(3,2,i);plot(x,y); % should go to figure 1
:
linearfittype = fittype({'0','x','1'});
f = fit(f,x,y);
subplot(3,2,i);plot(f,x,y); % should go to figure 2
end
How do I allocate the subplots to the appropriate figures?
If I understand correctly, it suffices to write figure(1) or figure(2) before the subplot statement.
If h is the handle or the Number property value of an existing figure, then figure(h) makes that existing figure the current figure, makes it visible, and moves it on top of all other figures on the screen. The current figure is the target for graphics output.
So:
%% Declare figures
figure(1); % Plot Measured (y) Vs Reference(x) data for 6 cases
figure(2); % Plot Regression fit for Measured vs Reference for 6 cases
%% Run algorithm for 6 cases
for i=1:6
:
:
figure(1) %// make figure 1 the current figure
subplot(3,2,i);plot(x,y); %// should go to figure 1
:
linearfittype = fittype({'0','x','1'});
f = fit(f,x,y);
figure(2) %// make figure 2 the current figure
subplot(3,2,i);plot(f,x,y); %// should go to figure 2
end

MATLAB: Dynamic heatmap

I have 3D matrix of dimensions D x D x N. I want to create a dynamic heatmap to show how it's varying over N. Here's the MATLAB code I used to achieve this.
for n=1:N
heatmap(dynamicCov(:,:,n));
pause(0.5);
end
The issue with this code is that for each n, it opens a new figure window. I want it to be updated in the same Heatmap window. Is it possible to do that? Is there any other way to achieve this?
Thanks.
You need to use the undocumented 2nd input to HeatMap that indicates whether a plot should be created or not, and a few other Handle Graphics tricks to get the handle to the figure that is created. Something like
data = rand(20,20,10); % create test data
hmo = HeatMap(data(:,:,1),false); % create but do not plot
plot(hmo); % do the plot
allHFig = findall(0,'Type','figure'); % get handle to all open figures
hFig = allHFig(1); % we want the most recently created figure
for idx = 2:size(data,3)
hmo = HeatMap(data(:,:,idx),false); % create heatmap but do not plot
plot(hmo,hFig); % plot to our existing figure
pause(0.5);
end
I found a better and a lot simpler way of doing this. It uses built in imagesc() function instead of HeatMap() function from Bioinformatics toolbox. The code is as follows:
dynamicCov = rand(20,20,10); % create test data
N = size(dynamicCov,3);
for n=1:N
imagesc(dynamicCov(:,:,n));
colormap('copper');
colorbar;
pause(0.5);
end
Reference: http://buli.waw.pl/matlab-heatmap-colormap/