i have a code that displays the CPU usage of Matlab, my problem is how to PLOT the CPU usage over time because the this code does NOT save any variables in the workspace,I need a method for storing the CPU usage in an array when the code is run so that i can plot it
Thanks for your time.
here is the code:
function hcol = CPU_monitor
h = create_gui;
end
function mon = createMonitor
MatlabProcess = System.Diagnostics.Process.GetCurrentProcess(); %// "Matlab" process
cpuIdleProcess = 'Idle';
mon.NumOfCPU = double(System.Environment.ProcessorCount);
mon.ProcPerfCounter.Matlab = System.Diagnostics.PerformanceCounter('Process', '% Processor Time', MatlabProcess.ProcessName);
mon.ProcPerfCounter.cpuIdle = System.Diagnostics.PerformanceCounter('Process', '% Processor Time', cpuIdleProcess);
end
function updateMeasure(obj,evt,hfig)
h = guidata(hfig);
%// Calculate the cpu usage
cpu.total = 100 - h.mon.ProcPerfCounter.cpuIdle.NextValue / h.mon.NumOfCPU;
cpu.matlab = h.mon.ProcPerfCounter.Matlab.NextValue / h.mon.NumOfCPU;
%// update the display
set(h.txtTotalCPU,'String',num2str(cpu.total,'%5.2f %%'))
set(h.txtMatlabCPU,'String',num2str(cpu.matlab,'%5.2f %%'))
end
function StartMonitor(obj,evt)
h = guidata(obj);
start(h.t)
end
function StopMonitor(obj,evt)
h = guidata(obj);
stop(h.t)
end
function h = create_gui %// The boring part
h.fig = figure('Unit','Pixels','Position',[200 800 240 120],'MenuBar','none','Name','CPU usage %','NumberTitle','off');
h.btnStart = uicontrol('Callback',#StartMonitor,'Position',[10 80 100 30],'String', 'START');
h.btnStart = uicontrol('Callback',#StopMonitor,'Position',[130 80 100 30 ],'String', 'STOP');
h.lbl1 = uicontrol('HorizontalAlignment','right','Position',[10 50 100 20],'String','TOTAL :','Style','text');
h.txtTotalCPU = uicontrol('Position',[130 50 100 20],'String','0','Style','text');
h.lbl2 = uicontrol('HorizontalAlignment','right','Position',[10 10 100 20],'String','Matlab :','Style','text');
h.txtMatlabCPU = uicontrol('Position',[130 10 100 20],'String','0','Style','text');
movegui(h.fig,'center')
%// create the monitor
h.mon = createMonitor;
%// Create the timer
h.t = timer;
h.t.Period = 0.25;
h.t.ExecutionMode = 'fixedRate';
h.t.TimerFcn = {#updateMeasure,h.fig};
h.t.TasksToExecute = Inf;
%// store the handle collection
guidata(h.fig,h)
end
one way is to save the variables to a file and read and plot it after you stop. So you add a dlmwrite command in the updateMeasure function, a tic to start the timer in StartMonitor, and dlmread and plot in StopMonitor. Of course this is quick and dirty as the file created will be needed to be deleted or checked so you wont continue to append to it in the later uses.
This is everything
function hcol = CPU_monitor
h = create_gui;
end
function mon = createMonitor
MatlabProcess = System.Diagnostics.Process.GetCurrentProcess(); %// "Matlab" process
cpuIdleProcess = 'Idle';
mon.NumOfCPU = double(System.Environment.ProcessorCount);
mon.ProcPerfCounter.Matlab = System.Diagnostics.PerformanceCounter('Process', '% Processor Time', MatlabProcess.ProcessName);
mon.ProcPerfCounter.cpuIdle = System.Diagnostics.PerformanceCounter('Process', '% Processor Time', cpuIdleProcess);
end
function updateMeasure(obj,evt,hfig)
h = guidata(hfig);
%// Calculate the cpu usage
cpu.total = 100 - h.mon.ProcPerfCounter.cpuIdle.NextValue / h.mon.NumOfCPU;
cpu.matlab = h.mon.ProcPerfCounter.Matlab.NextValue / h.mon.NumOfCPU;
dlmwrite('cpulog.txt', [toc, cpu.total , cpu.matlab], '-append');
%// update the display
set(h.txtTotalCPU,'String',num2str(cpu.total,'%5.2f %%'))
set(h.txtMatlabCPU,'String',num2str(cpu.matlab,'%5.2f %%'))
end
function StartMonitor(obj,evt)
h = guidata(obj);
start(h.t)
tic
end
function StopMonitor(obj,evt)
h = guidata(obj);
stop(h.t)
data=dlmread('cpulog.txt');
data(1,:)=[];
figure;plot(data(:,1),data(:,2),data(:,1) ,data(:,3));
legend('total cpu','matlab cpu'); xlabel('sec'); ylabel('%');
end
function h = create_gui %// The boring part
h.fig = figure('Unit','Pixels','Position',[200 800 240 120],'MenuBar','none','Name','CPU usage %','NumberTitle','off');
h.btnStart = uicontrol('Callback',#StartMonitor,'Position',[10 80 100 30],'String', 'START');
h.btnStart = uicontrol('Callback',#StopMonitor,'Position',[130 80 100 30 ],'String', 'STOP');
h.lbl1 = uicontrol('HorizontalAlignment','right','Position',[10 50 100 20],'String','TOTAL :','Style','text');
h.txtTotalCPU = uicontrol('Position',[130 50 100 20],'String','0','Style','text');
h.lbl2 = uicontrol('HorizontalAlignment','right','Position',[10 10 100 20],'String','Matlab :','Style','text');
h.txtMatlabCPU = uicontrol('Position',[130 10 100 20],'String','0','Style','text');
movegui(h.fig,'center')
%// create the monitor
h.mon = createMonitor;
%// Create the timer
h.t = timer;
h.t.Period = 0.25;
h.t.ExecutionMode = 'fixedRate';
h.t.TimerFcn = {#updateMeasure,h.fig};
h.t.TasksToExecute = Inf;
%// store the handle collection
guidata(h.fig,h)
end
Related
I have code that breaks up a sound file into 1 sec chunks, calculates the RMS of the chunk, then plots all chunks. It works fine until I edited it to make it read through a folder rather than one user loaded file at at time. Now it prints every value of fs (all 32k) which obviously massively slows down the script. Here is the new script:
DirIn = 'D:\Trial'
eval(['filelist=dir(''' DirIn '/*.wav'')'])
for i = 1:length(filelist)
[y,fs] = audioread(strcat(DirIn,'/',filelist(i).name))
npts = length(y);
chunkDur = 1; % length of chunk to analyze in seconds
systemCal = 0; % this should be whatever dB corresponds to an amplitude of 1 in wav file
chunkPts = fs * chunkDur;
rms = [];
for i = 1:chunkPts:npts-chunkPts
chunkRMS = 20 * log10(std(y(i: i + chunkPts))) + systemCal; % rms of chunk in dB
rms = [rms; chunkRMS];
end
t = [0: length(rms) - 1] * chunkDur; % time scale
plot(t, rms)
xlabel('Time (s)');
ylabel('RMS dB');
end
For reference, here's the original that works:
npts = length(data);
chunkDur = 1; % length of chunk to analyze in seconds
systemCal = 0; % this should be whatever dB corresponds to an amplitude of 1 in wav file
chunkPts = fs * chunkDur;
rms = [];
for i = 1:chunkPts:npts-chunkPts
chunkRMS = 20 * log10(std(data(i: i + chunkPts))) + systemCal; % rms of chunk in dB
rms = [rms; chunkRMS];
end
t = [0: length(rms) - 1] * chunkDur; % time scale
plot(t, rms)
xlabel('Time (s)');
ylabel('RMS dB');
You missed a semicolon ; at the end of line [y,fs] = audioread(strcat(DirIn,'/',filelist(i).name)).
It signifies the end of a row and suppress an output of the code line. There is a nice blog-entry on this here.
I am trying to plot clusters via the MATLAB function kmean but am getting way too many centroids and have no idea why. Here is my code and an example of a figure:
rng(1);
wv_prop = [min_pts(:) slope(:)];
if (isempty(wv_prop)==0)
[idx,C] = kmeans(wv_prop,2);
subplot(3,2,5);
plot(wv_prop(idx==1,1),wv_prop(idx==1,2),'b.','MarkerSize',12);
hold on
plot(wv_prop(idx==2,1),wv_prop(idx==2,2),'r.','MarkerSize',12);
plot(C(:,1),C(:,2),'kx',...
'MarkerSize',15,'LineWidth',3)
Here is an example of the data I use:
wv_prop:
-7.50904246127179e-05 2.52737793199461e-05
-7.64715493632322e-05 -29.2845021783221
-8.16630514296111e-05 -15.5896244315076
-8.60516901697005e-05 3.87325886247646e-05
-9.07390060961131e-05 4.06844795948271e-05
-7.93980060844007e-05 3.72806601486833e-05
-8.08420950480078e-05 3.81372062193057e-05
-8.53045358845788e-05 4.00072285969318e-05
-7.07712622172574e-05 3.55502071296987e-05
-8.02846575361635e-05 3.91085777803079e-05
-8.82904795076420e-05 4.21557386394776e-05
-8.32088783242009e-05 4.08103587885502e-05
-8.17564769131708e-05 4.06201592898485e-05
-8.88574631122910e-05 4.31980154605407e-05
-9.55496137235401e-05 4.55119867638717e-05
-7.11241881995855e-05 3.72772062250438e-05
-8.20641318582800e-05 6.09118479264444e-05
-7.92369664739745e-05 5.86246041439769e-05
-7.61219361068837e-05 5.57318660221894e-05
-8.52918510230295e-05 5.84710267850959e-05
-8.99668387994064e-05 5.84558301867090e-05
-9.62926333243702e-05 5.87762601336998e-05
-7.87678776488358e-05 4.67111894400931e-05
-7.53525297201741e-05 4.13207831828739e-05
-7.71766983561651e-05 3.82625914011195e-05
-9.03499693359608e-05 4.06874790212135e-05
-7.59387077492098e-05 2.92390401569819e-05
-7.97649576465785e-05 32.1683359898974
-8.06408560217508e-05 1.55409105433306e-05
-8.10515208048491e-05 1.31180389653758e-05
-7.70540121076476e-05 9.43353748786386e-06
-7.24001267378072e-05 5.78599898248438e-06
-8.93350436455590e-05 9.61034087028361e-06
-7.97722332494743e-05 4.89104076311932e-06
-8.40022599007737e-05 5.06726288587479e-06
-7.89655937936233e-05 2.44686642783556e-06
-8.58007004774045e-05 4.06628163987085e-06
-7.68775819259902e-05 1.06146142996962e-06
-7.05769224846652e-05 -2.25666633700963e-06
-7.73022200637920e-05 1.34546072255262e-06
-7.65784897728499e-05 1.62917829786978e-06
-7.41548367397790e-05 1.46536230997079e-06
-9.17371298592096e-05 1.17025036839378e-05
-7.35354500231489e-05 4.43710161064086e-06
function [] = Select_Figs(filename,startblock,endblock,startclust,endclust,animal,day)
%Select_Figs - Plots average waveforms, standard deviation, difference over time,
%fitted peak location histogram, mean squared error, k-mean clustered peak location and slope,
%and raw waveforms across selected blocks and clusters,
%saves to folder Selected-Figures-animal-date
%
%Select_Figs(filename,startblock,endblock,startclust,endclust,animal,date)
%
%filename - Sort.mat(e.g. = 'Sort.mat')
%
%startblock- first block (e.g. = 7)
%
%endblock - last block (e.g. = 12)
%
%startclust - first cluster (e.g. = 5)
%
%endclust - last cluster (e.g. = 10)
%
%animal - animal number (e.g. = 12)
%
%date - start of experiment (e.g. = 101617)
%
%Function called by User_Sort.m
Sort = filename;
addpath(pwd);
%Get Sort file
foldername = sprintf('Selected-Figures-%s-%s',animal,day); %Creates dynamic folder name to store figures
mkdir(foldername); %Makes directory
cd(fullfile(foldername)); %Cd to new directory
tvec = 0:.013653333:(.013653333*97); %Time vector
t = tvec(2:end);
for clust = startclust:endclust %Loops through all clusters
fig = cell(1,endblock); %Preallocate # of figures
name = sprintf('Idx_%d',clust); %Individual cluster name
fig{clust} = figure('Visible', 'off'); %Turns figure visibility off
for block = startblock:endblock %Loop through all blocks
wvfrms_avg =Sort.(name)(block).avg;
wvfrms_avg_scaled = (wvfrms_avg*10^6);
wvfrms_std =Sort.(name)(block).standdev;
min_ind = wvfrms_avg_scaled == min(wvfrms_avg_scaled);
min_loc = t(min_ind);
[~,io] = findpeaks(wvfrms_avg_scaled);
leftmin = io<find(wvfrms_avg_scaled==min(wvfrms_avg_scaled));
leftmin = leftmin(leftmin~=0);
rightmin = io>find(wvfrms_avg_scaled==min(wvfrms_avg_scaled));
rightmin = rightmin(rightmin~=0);
if (isempty(wvfrms_avg_scaled)==0)
subplot(3,2,1);
if (isnan(wvfrms_avg_scaled)==0)&((-30<min(wvfrms_avg_scaled))||(min_loc>0.55)||(min_loc<0.3)||(length(io(leftmin))>2)||(length(io(rightmin))>2))
plot(tvec(1:end-1),wvfrms_avg_scaled,'r');
else
plot(tvec(1:end-1),wvfrms_avg_scaled,'b');
end
end
new_wv = wvfrms_avg_scaled(40:end);
[~,locs_scaled] = findpeaks(new_wv);
if isempty(locs_scaled)==1
ind_scaled = max(new_wv);
else
ind_scaled = locs_scaled(1);
end
x1_scaled = new_wv(find(min(wvfrms_avg_scaled)));
y1_scaled = min(wvfrms_avg_scaled);
x2_scaled = ind_scaled;
y2_scaled = new_wv(find(ind_scaled));
slope_scaled= (y2_scaled-y1_scaled)./(x2_scaled-x1_scaled);
if (isnan(wvfrms_avg_scaled)==0)
if ((-30<min(wvfrms_avg_scaled)))
lab = sprintf('Time (ms) \n Peak exceeds amplitude range (%s)',num2str(min(wvfrms_avg_scaled)));
xlabel(lab,'FontSize',8);
ylabel('Mean Voltage (\muV)','FontSize',8);
title('Average Waveform','FontSize',8);
elseif ((min_loc>0.55)||(min_loc<0.3))
lab = sprintf('Time (ms) \n Peak location exceeds range (Time = %s)',num2str(min_loc));
xlabel(lab,'FontSize',8);
ylabel('Mean Voltage (\muV)','FontSize',8);
title('Average Waveform','FontSize',8);
elseif (length(io(leftmin))>2)||(length(io(rightmin))>2)
lab = sprintf('Time (ms) \n Peak limit exceeded (# = %s) Peak = %s',num2str(length(io)),num2str(min(wvfrms_avg_scaled)));
xlabel(lab,'FontSize',8);
ylabel('Mean Voltage (\muV)','FontSize',8);
title('Average Waveform','FontSize',8);
else
lab = sprintf('Time (ms) \n Peak = %s Slope = %s',num2str(min(wvfrms_avg_scaled)),num2str(slope_scaled));
xlabel(lab,'FontSize',8)
ylabel('Mean Voltage (\muV)','FontSize',8);
title('Average Waveform','FontSize',8);
end
end
if (isempty(wvfrms_std)==0&isempty(wvfrms_avg)==0)
subplot(3,2,2);
errorbar(t,wvfrms_avg,wvfrms_std); %Plots errorbars
end
wvfrms_num_text = sprintf(['Time (ms) \n # Waveforms: ' num2str(size(Sort.(name)(block).block,2))]);
xlabel(wvfrms_num_text,'FontSize',8);
ylabel('Mean Voltage (V)','FontSize',8);
title('Average Waveform + STD','FontSize',8);
wvfrms = Sort.(name)(block).block;
for i = 1:size(wvfrms,1)
if isempty(wvfrms)==0
min_pts = min(wvfrms,[],2); %Adds array of min wvfrm points to matrix
slope = zeros(1,size(wvfrms,1));
new = wvfrms(i,:);
new_cut = new(40:end);
[~,locs] = findpeaks(new_cut);
if isempty(locs)==1
ind = max(new_cut);
else
ind = locs(1);
end
x1 = new(find(min_pts(i)));
y1 = min_pts(i);
x2 = ind;
y2 = new(find(ind));
slope(i) = (y2-y1)./(x2-x1);
else
slope(i) = 0;
end
end
bins = 100;
hist_val = (min_pts(:)*10^6);
if isempty(hist_val)==0
%Convert matrix of min points to array and into microvolts
subplot(3,2,3);
histogram(hist_val,bins);
ylabel('Count','FontSize',8);
title('Waveform Peaks','FontSize',8);
cnt = histcounts(hist_val,bins); %Returns bin counts
line_fit = zeros(1,length(cnt)); %Preallocates vector to hold line to fit histogram
for i = 3:length(line_fit)-3
if (cnt(i)<mean(cnt)) %If bin count is less than mean, take mean of 3
cnt(i)=mean([cnt(i-1) cnt(i+1)]); %consecutive bins, set as bin count
end
if (mean([cnt(i-2) cnt(i-1) cnt(i) cnt(i+1) cnt(i+2)])>=mean(cnt)) %If mean of 5 consecutive bins
line_fit(i-1) = (max([cnt(i-2) cnt(i-1) cnt(i) cnt(i+1) cnt(i+2)]));%exceeds bin count, set max,
end %add to line fit vector
end
line_fit(line_fit<=mean(cnt)) = min(cnt)+1; %Set line_fit values less than mean
x = linspace(min(hist_val),max(hist_val),length(line_fit)); %X axis (min - max point of vals)
hold on
plot(x,line_fit,'k','LineWidth',1.5);
assignin('base','hist_val',hist_val);
if (isempty(hist_val)==0)
gm = fitgmdist(hist_val,2,'RegularizationValue',0.1);
warning('off','stats:gmdistribution:FailedToConverge');
comp1 = gm.ComponentProportion(1)*100;
comp2 = gm.ComponentProportion(2)*100;
mean1 = gm.mu(1);
mean2 = gm.mu(2);
hist_leg = sprintf('\\muV \n Component 1 = %0.2f%% Component 2 = %0.2f%% \n Mean 1 = %0.2f Mean 2 = %0.2f',comp1,comp2,mean1,mean2);
xlabel(hist_leg,'FontSize',8);
end
hold off
else
subplot(3,2,3);
hist_val = 0;
plot(hist_val);
end
hist_val = (slope(:)*10^3);
if isempty(hist_val)==0
subplot(3,2,4);
histogram(hist_val,bins);
ylabel('Count');
cnt = histcounts(hist_val,bins); %Returns bin counts
line_fit = zeros(1,length(cnt)); %Preallocates vector to hold line to fit histogram
for i = 3:length(line_fit)-3
if (cnt(i)<mean(cnt)) %If bin count is less than mean, take mean of 3
cnt(i)=mean([cnt(i-1) cnt(i+1)]); %consecutive bins, set as bin count
end
if (mean([cnt(i-2) cnt(i-1) cnt(i) cnt(i+1) cnt(i+2)])>=mean(cnt)) %If mean of 5 consecutive bins
line_fit(i-1) = (max([cnt(i-2) cnt(i-1) cnt(i) cnt(i+1) cnt(i+2)])); %exceeds bin count, set max,
end %add to line fit vector
end
line_fit(line_fit<=mean(cnt)) = min(cnt)+1; %Set line_fit values less than mean
x = linspace(min(hist_val),max(hist_val),length(line_fit)); %X axis (min - max point of vals)
hold on
plot(x,line_fit,'k','LineWidth',1.5);
gm = fitgmdist(hist_val,2,'RegularizationValue',0.1);
warning('off','stats:gmdistribution:FailedToConverge');
comp1 = gm.ComponentProportion(1)*100;
comp2 = gm.ComponentProportion(2)*100;
mean1 = gm.mu(1);
mean2 = gm.mu(2);
title('Waveform Slope','FontSize',8);
hist_leg = sprintf('Slope (m) \n Component 1 = %0.2f%% Component 2 = %0.2f%% \n Mean 1 = %0.2f Mean 2 = %0.2f',comp1,comp2,mean1,mean2);
xlabel(hist_leg,'FontSize',8);
hold off
else
subplot(3,2,4);
hist_val = 0;
plot(hist_val);
end
rng(1);
wv_prop = [min_pts(:) slope(:)];
if (isempty(wv_prop)==0)
[idx,C] = kmeans(wv_prop,2);
subplot(3,2,5);
plot(wv_prop(idx==1,1),wv_prop(idx==1,2),'b.','MarkerSize',12);
hold on
plot(wv_prop(idx==2,1),wv_prop(idx==2,2),'r.','MarkerSize',12);
plot(C(:,1),C(:,2),'kx',...
'MarkerSize',15,'LineWidth',3)
title('Clustered Peak and Slope','FontSize',8);
fig_about = sprintf('BL%s - Cluster %s Block %s', animal,num2str(clust),num2str(block));
figtitle(fig_about);
else
subplot(3,2,5);
wv_prop = 0;
plot(wv_prop);
end
if isempty(wvfrms)==0
[vals] = align_wvs(wvfrms);
if (~isempty(vals))
subplot(3,2,6);
plot(t,vals);
title('Raw Waveforms','FontSize',8);
end
else
subplot(3,2,6);
w = 0;
plot(w);
end
print(fig{clust},['Cluster-' num2str(clust) ' Block-' num2str(block)],'-dpng');
end
end
disp('Done');
end
I'm planning to plot a graph of velocity against time using matlab. The change of time is 0.05 and total time 15. When time change, the graph will change and save a figure of that. I had mat file which contained all the data for time and velocity.
E.g, t=0, v=0, plot and save, t=0.05, v=1, plot and save until t=15.
I tried to use v=v+1 (which acts like i++) but failed to read the value of v in 2nd row. Any other method to do so?
Thank You.
The code is
i = 001
dt = t(2,1) - t(1,1);
k = dt*(i-1);
filename1 = 'front_data';
matFileName = sprintf('%s.mat', filename1);
matData = load(matFileName);
t = matData.time;
fv = matData.front_velocity;
fig = figure%('visible', 'off');
s = t(1,1);
fv = fv(1,1);
lot (s,fv,'*')
pic_filename = sprintf('front_data%02d.jpeg', k);
print(fig,pic_filename,'-djpeg')
istart = 002
iend = 301
for i = istart:iend
k = dt*(i-1);
t = t+dt
filename1 = 'front_data';
matFileName = sprintf('%s.mat', filename1);
matData = load(matFileName);
t = matData.time;
fv = matData.front_velocity;
v = fv(1,1);
v = v+1;
h = figure
axis([0 15 0 0.6])
plot(t,v,'*')
pic_filename = sprintf('front_data%02d.jpeg', k);
print(h,pic_filename,'-djpeg')
end
And the example I refer is the [https://www.mathworks.com/matlabcentral/answers/110632-how-to-increment-a-variable]
I reduced your example to the essential parts.
istart = 2;
iend = 301;
counter=istart;
%load data
% filename1 = 'front_data';
% matFileName = sprintf('%s.mat', filename1);
% matData = load(matFileName);
% t = matData.time;
% fv = matData.front_velocity;
%for demonstaration
t=0:.05:15;
fv=rand(size(t));
for i = istart:iend
%update
time = t(istart:counter);
values = fv(istart:counter);
%plot
plot(time,values,'*')
%increase index
counter=counter+1;
end
As you are loading always the same data in the loop you can do it once outside the loop, and for plotting you just update the length of your vector to be plotted. You could also just append the new value to the actual list.
In the first Matlab script below when I run it as shown I get no errors what so ever and the code produces the expected results, however when I take out matlabpool open and matlabpool close as well as changing the parfor loop to a for loop, I get the following error:
Running... ??? Error using ==> mldivide
Matrix is singular to working precision.
Error in ==> NSS_betas at 11
betas = G\data.y2.';
Error in ==> DElambda at 19
betas(:,ii) = NSS_betas(P1(:,ii),data); end
Error in ==> Individual_Lambdas at 46
beta{ii} = DElambda(de,dataList, #OF_NSS);
I will happily send CRM_22_12.mat if required.
Why does the error only trigger when I use a regular for loop instead if a parfor loop?
clear all, clc
load Euro_CRM_22_12.mat
matlabpool open
tic
warnState(1) = warning('error', 'MATLAB:singularMatrix');
warnState(2) = warning('error', 'MATLAB:illConditionedMatrix');
mats = 1:50;
mats2 = [2 5 10 30];
% RO: unloop these
de = struct(...
'min', [0;0],...
'max', [50;50],...
'd' , 2,...
'nP' , 500,...
'nG' , 600,...
'ww' , 0.1,...
'F' , 0.5,...
'CR' , 0.99,...
'R' , 0,...
'oneElementfromPm',1);
% RO: initialize beta
beta = cell(size(rates,1),1);
clc, fprintf('Running... ');
%for ii = 1:size(rates,1)
parfor ii = 1:size(rates,1)
% RO: use status indicator for things that take this long
%fprintf('\b\b\b\b\b\b\b%6.2f%%', ii/size(rates,1)*100);
dataList = struct(...
'yM' , rates(ii,:),...
'mats' , mats,...
'model', #NSS,...
'mats2', mats2,...
'y2' , rates(ii,mats2));
beta{ii} = DElambda(de,dataList, #OF_NSS);
end
toc
matlabpool close
%
function [output] = DElambda(de,data,OF)
% RO: also saves time
% warning off; %#ok
warning on verbose;
P1 = zeros(de.d,de.nP);
Pu = zeros(de.d,de.nP);
for ii = 1:de.d
P1(ii,:) = de.min(ii,1)+(de.max(ii,1)-de.min(ii,1))*rand(de.nP,1); end
P1(:,1:de.d) = diag(de.max);
P1(:,de.d+1:2*de.d) = diag(de.min);
% RO: pre allocate betas
betas = zeros(size(data.y2,2), de.nP);
for ii = 1:de.nP
betas(:,ii) = NSS_betas(P1(:,ii),data); end
Params = vertcat(betas,P1);
Fbv = NaN(de.nG,1);
% must pass OF as #OF
F = zeros(de.nP,1);
P = zeros(de.nP,1);
for ii = 1:de.nP
F(ii) = OF(Params(:,ii)',data);
P(ii) = pen(P1(:,ii),de,F(ii));
F(ii) = F(ii)+P(ii);
end
[Fbest indice] = min(F);
xbest = Params(:,indice);
Col = 1:de.nP;
% RO: pre allocate betasPu
betasPu = zeros(size(data.y2,2), de.nP);
% RO: if Fbest hasn't changed for 25 generations,
% it's not gonna anymore: break off
count = 0;
for g = 1:de.nG
P0 = P1;
rowS = randperm(de.nP).';
colS = randperm(4).';
% RO: replace circshift for JIT accelleration
% RS = circshift(rowS,colS(1));
% R1 = circshift(rowS,colS(2));
% R2 = circshift(rowS,colS(3));
% R3 = circshift(rowS,colS(4));
RS = rowS([end-colS(1)+1:end 1:end-colS(1)]);
R1 = rowS([end-colS(2)+1:end 1:end-colS(2)]);
R2 = rowS([end-colS(3)+1:end 1:end-colS(3)]);
R3 = rowS([end-colS(4)+1:end 1:end-colS(4)]);
% mutate
Pm = P0(:,R1) + de.F*(P0(:,R2)-P0(:,R3));
if de.R>0, Pm = Pm+de.r*randn(de.d,de.nP); end
% crossover
PmElements = rand(de.d,de.nP)<de.CR;
if de.oneElementfromPm
% RO: JIT...
%Row = unidrnd(de.d,1,de.nP);
Row = ceil(de.d .* rand(1,de.nP));
ExtraPmElements = sparse(Row,Col,1,de.d,de.nP);
PmElements = PmElements|ExtraPmElements;
end
P0_Elements = ~PmElements;
Pu(:,RS) = P0(:,RS).*P0_Elements+PmElements.*Pm;
% RO: inline NSS_betas, so that this loop can
% be compiled by the JIT
mats = data.mats2.';
yM = data.y2.';
nObs = size(data.y2,2);
one = ones(nObs,1);
% RO: version below is faster
% for ii = 1:de.nP
% %betasPu(:,ii) = NSS_betas(Pu(:,ii),data);
%
% lambda = Pu(:,ii);
% G = [one,...
% (1-exp(-mats/lambda(1)))./(mats/lambda(1)),...
% ((1-exp(-mats/lambda(1)))./(mats/lambda(1)) - exp(-mats/lambda(1))),...
% ((1-exp(-mats/lambda(2)))./(mats/lambda(2)) - exp(-mats/lambda(2)))];
%
% betasPu(:,ii) = G\yM;
%
% end
aux = bsxfun(#rdivide, mats, Pu(:).');
aux2 = exp(-aux);
aux3 = (1-aux2)./aux;
for ii = 1:2:2*de.nP
% betasPu(:,(ii+1)/2) =[...
% one,...
% aux3(:,ii),...
% aux3(:,ii) - aux2(:,ii),...
% aux3(:,ii+1) - aux2(:,ii+1)] \ yM;
G=[one, aux3(:,ii), aux3(:,ii) - aux2(:,ii),aux3(:,ii+1) - aux2(:,ii+1)];
try
betasPu(:,(ii+1)/2) =G\yM;
catch ME
CondPen(1,(ii+1)/2)=0;
end
end
ParamsPu = [betasPu;Pu];
flag = 0;
mats = data.mats;
yM = data.yM;
for ii = 1:de.nP
% RO: inline OF_NSS.m here for JIT accelleration
%Ftemp = OF(ParamsPu(:,ii).',data);
beta = ParamsPu(:,ii).';
%model = data.model;
yy = zeros(size(yM));
for jj = 1:size(beta,3)
% RO: inline for JIT accelleration
%y(ii,:) = model(beta(:,:,ii),mats);
betai = beta(:,:,jj);
gam1 = mats/betai(5);
gam2 = mats/betai(6);
aux1 = 1-exp(-gam1);
aux2 = 1-exp(-gam2);
% I have a feeling this is the same as G and therefore
% this can be done shorter and quicker...
% something like yy(jj,:) = sum(G,2)
yy(jj,:) = ...
betai(1) + ...
betai(2)*(aux1./gam1) + ...
betai(3)*(aux1./gam1+aux1-1) + ...
betai(4)*(aux2./gam2+aux2-1);
end
yy = yy-yM;
% RO: this whole loop can be replaced...
% ObjVal = 0;
% for i = 1:size(yM,1) %dim
% ObjVal = ObjVal+dot(aux(i,:)',aux(i,:)');
% %ObjVal = sum(ObjVal);
% end
% ObjVal
% RO ...by this one-liner
Ftemp = sum(yy(:).^2);
% RO: inline penalty here as well
Ptemp = 0;%pen(Pu(:,ii),de,F(ii));
Ftemp = Ftemp+Ptemp;%+CondPen(1,ii);
if Ftemp <= F(ii);
P1(:,ii) = Pu(:,ii);
F(ii) = Ftemp;
if Ftemp < Fbest
Fbest = Ftemp; xbest = ParamsPu(:,ii);
flag = 1;
count = 0;
end
else
P1(:,ii) = P0(:,ii);
end
end
if flag
Fbv(g) = Fbest; end
% RO: if Fbest hasn't changed for 25 generatios, break off
count = count + 1;
if count > 25, break; end
end
output.Fbest = Fbest;
output.xbest = xbest;
output.Fbv = Fbv;
end
% look to inline penalty later (i.e. incoporate into code
function penVal = pen(~,~,~)%pen(beta,pso,vF,data)
penVal = 0;
end
%
function [betas r r2] = NSS_betas(lambda,data)
mats = data.mats2.';
nObs = size(data.y2,2);
G = [ones(nObs,1),...
(1-exp(-mats/lambda(1)))./(mats/lambda(1)),...
((1-exp(-mats/lambda(1)))./(mats/lambda(1)) - exp(-mats/lambda(1))),...
((1-exp(-mats/lambda(2)))./(mats/lambda(2)) - exp(-mats/lambda(2)))];
betas = G\data.y2.';
% RO: output hardly ever needed, while rank()
% is very time consuming
if nargout > 1 && ~isnan(G)
r = rank(G);
r2 = rcond(G);
end
end
It's a bit cryptic, but here's what I can tell you for sure.
Error in ==> NSS_betas at 11
betas = G\data.y2.';
Error in ==> DElambda at 19
betas(:,ii) = NSS_betas(P1(:,ii),data); end
Error in ==> Individual_Lambdas at 46
beta{ii} = DElambda(de,dataList, #OF_NSS);
Essentially, this means that the G matrix is singular, and thus doesn't have a solution. That would be this:
G = [ones(nObs,1),...
(1-exp(-mats/lambda(1)))./(mats/lambda(1)),...
((1-exp(-mats/lambda(1)))./(mats/lambda(1)) - exp(-mats/lambda(1))),...
((1-exp(-mats/lambda(2)))./(mats/lambda(2)) - exp(-mats/lambda(2)))];
betas = G\data.y2.';
What I would do to further diagnose this is to set the stop on error flag. There is a few ways to do this, one from the gui, and another via command. Take a look to see if the matrix looks correct. Odds are, something isn't right. Trace back the error, and you'll figure it out.
I have two GUI-s.
the first GUI is named: GUI1, there the user inserts three values.
then the user has a button 'Submit', so I want these values to be sent to other function (GUI2) every time he presses it.
my function GUI2.m gets three elements:
function GUI2(x,y,r)
.
.
.
end
and this is the first GUI:
function [E] = GUI1()
num_of_columns = 3;
E = []; % In case the user closes the GUI.
S.fh = figure('units','pixels',...
'position',[500 500 850 100],...
'menubar','none',...
'name','Number Of Columns',...
'numbertitle','off',...
'resize','off');
num = 0;
for i = 1:num_of_columns
S.ed(i) = uicontrol('style','edit',...
'units','pix',...
'position',[num 60 100 30],...
'string','');
num = num + 500/num_of_columns;
uicontrol(S.ed(1)) % Make the editbox active.
end
S.pb = uicontrol('style','pushbutton',...
'units','pix',...
'position',[290 20 180 30],...
'string','Submit',...
'callback',{#pb_call});
uiwait(S.fh) % Prevent all other processes from starting until closed.
function [] = pb_call(varargin)
% Callback for the pushbutton.
E = get(S.ed(:),'string');
E{1} = str2num(E{1});
E{2} = str2num(E{2});
E{3} = str2num(E{3});
In this line I want to send E{1}, E{2} and E{3} to GUI2
end
end
how about:
GUI2(E{1},E{2},E{3})