text
stringlengths 8
6.12M
|
|---|
function [ bs, block ] = Score( s, DNA, n)
% s - odkud začíná konsenzus
% DNA - typ cell, ve které jsou zadané sekvence
% n - jak bude konsenzus dlouhý (jak daleko od začátku je konec konsenzusu)
% bs .. to skóre součet maxim (frekvence)
% block .. výpis o jaké konsenzy se jednalo
for i = 1: length(DNA)
block(i,:) = DNA{1, i}(s(i):s(i)+n-1);
end
for j = 1:length(block)
sum_A(j) = length(find(block(:,j)=='A'));
sum_C(j) = length(find(block(:,j)=='C'));
sum_T(j) = length(find(block(:,j)=='T'));
sum_G(j) = length(find(block(:,j)=='G'));
end
ACTG =[sum_A;sum_C;sum_T;sum_G];
for q=1:length(ACTG)
pom(q) = max(ACTG(:,q));
end
bs = sum(pom);
end
|
clc
clear
close all
labeltsize=25;
fw = 'normal'; %%是否加粗斜体之类
fn='Times New Roman';
linewide1=5;
mkft = 15;
load 2N.mat
figure(1);
hold on
plot(SNRout,Pd_SGLRT_mc,'k-o','linewidth',linewide1,'MarkerSize',5)
plot(SNRout,Pd_SRAO_mc,'r-x','linewidth',linewide1,'MarkerSize',mkft)
plot(SNRout,Pd_SWALD_mc,'b-x','linewidth',linewide1,'MarkerSize',mkft)
h_leg=legend('GLRT','RAO','WALD');
xlabel('SNR(dB)','FontSize',labeltsize,'FontWeight',fw,'FontName',fn)
ylabel('PD','FontSize',labeltsize,'FontWeight',fw,'FontName',fn)
set(gca,'FontSize',labeltsize)
set(gcf,'Position',[700 0 1300 1000])
set(h_leg,'Location','NorthWest')
grid on
box on
str=['SNR2N.eps'];
print(gcf,'-depsc',str) %保存为png格式的图片到当前路径
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load 10N.mat
figure(2);
hold on
plot(SNRout,Pd_SGLRT_mc,'k-o','linewidth',linewide1,'MarkerSize',5)
plot(SNRout,Pd_SRAO_mc,'r-x','linewidth',linewide1,'MarkerSize',mkft)
plot(SNRout,Pd_SWALD_mc,'b-x','linewidth',linewide1,'MarkerSize',mkft)
h_leg=legend('GLRT','RAO','WALD');
xlabel('SNR(dB)','FontSize',labeltsize,'FontWeight',fw,'FontName',fn)
ylabel('PD','FontSize',labeltsize,'FontWeight',fw,'FontName',fn)
set(gca,'FontSize',labeltsize)
set(gcf,'Position',[700 0 1300 1000])
set(h_leg,'Location','NorthWest')
grid on
box on
str=['SNR10N.eps'];
print(gcf,'-depsc',str) %保存为png格式的图片到当前路径
pause(1)
close all
|
% determine the 3dB mainlobe width
function res = res(af, delay_delta)
s = size(af);
res = zeros(s(1),1);
% loop across the Doppler axis
for jj=1:s(1)
% figure out the mainlobe boundary for this slice
[~, mid] = max(af(jj,:));
the_max = 0;
the_min = 0;
for ii=mid:s(2)
if af(jj,ii) < 0.5
the_max = ii-1;
break;
end
end
for ii=mid-1:-1:1
if af(jj,ii) < 0.5
the_min = ii+1;
break;
end
end
res(jj) = (the_max-the_min)*delay_delta;
end
end
|
function analyzesim(varargin)
% function analyzesim(filename,opts)
% or analyzesim()
% Runs the standard set of analysis procedures on a file, or in the base workspace.
% Calculates center of mass, swimming direction, kinematic parameters,
% muscle work, fluid stress and energy. Saves to an output file
% ('outfile',filename).
opt.curvesmoothcutoff = 0.025; % filter cutoff for curvature
% opt.nboundarypts = 30;
opt.steadythresh = 0.05; % threshold velocity fluctuation. Less than this is "steady"
opt.steadydX = 0.03; % threshold velocity fluctuation. Less than this is "steady"
opt.leftsidecurvature = -1; % definition of "left" in terms of curvature
opt.leftsidepeak = 1; % definition of "left" in terms of peak direction
% peak finding procedure
% Look for local max/min. Find points > pkthresh*max. Peak is center
% of all neighboring points > pkthresh*max.
opt.pkthresh = 0.9;
opt.outfile = ''; % output file name
opt.samraibasedir = ''; % base directory for all the samrai data files
opt.rho = 1; % density in CGS units
opt.savepressure = false;
opt.savevorticity = false;
if ((nargin >= 1) && ischar(varargin{1}) && ...
exist(varargin{1},'file')),
datafilename = varargin{1};
fprintf('**** File %s\n', varargin{1});
filenameopt = {'-file',varargin{1}};
p = 2;
else
fprintf('Base workspace\n');
datafilename = '';
filenameopt = {};
p = 1;
end;
opt = parsevarargin(opt, varargin(p:end), p);
% necessary variables
disp(' Loading variables...');
if (~getvar(filenameopt{:}, 'actl','actr','fmusPl','fmusPr',...
'fxlmus','fxltot','fxmtot','fxntot','fxrmus','fxrtot',...
'fylmus','fyltot','fymtot','fyntot','fyrmus','fyrtot',...
't','xl','yl','xm','ym','xn','yn','xr','yr',...
'ul','vl','um','vm','un','vn','ur','vr'))
error('Could not find necessary variables');
end;
if (getvar(filenameopt{:}, 'good')),
actl = actl(:,good);
actr = actr(:,good);
fmusPl = fmusPl(:,good);
fmusPr = fmusPr(:,good);
fxlmus = fxlmus(:,good);
fxrmus = fxrmus(:,good);
fylmus = fylmus(:,good);
fyrmus = fyrmus(:,good);
fxmtot = fxmtot(:,good);
fymtot = fymtot(:,good);
fxntot = fxntot(:,good);
fyntot = fyntot(:,good);
fxltot = fxltot(:,good);
fyltot = fyltot(:,good);
fxrtot = fxrtot(:,good);
fyrtot = fyrtot(:,good);
t = t(good);
xl = xl(:,good);
yl = yl(:,good);
xm = xm(:,good);
ym = ym(:,good);
xn = xn(:,good);
yn = yn(:,good);
xr = xr(:,good);
yr = yr(:,good);
ur = ur(:,good);
vr = vr(:,good);
um = um(:,good);
vm = vm(:,good);
un = un(:,good);
vn = vn(:,good);
ul = ul(:,good);
vl = vl(:,good);
end;
%optional variables
%default values:
disp(' Getting the simulation parameters...');
freq = 1;
viscosity = 0.01;
sfo = 2.56e6;
sfo2 = '';
ps = 3;
gridres = 32;
isforcetaper = 'true';
if (~getvar(filenameopt{:}, 'freq','viscosity','sfo','sfo2','ps','gridres','isforcetaper',...
'-keepundef')),
prompt = {'freq','viscosity','sfo','sfo2','ps','gridres','isforcetaper'};
def = cellfun(@num2str,{freq,viscosity,sfo,sfo2,ps,gridres,isforcetaper},'UniformOutput',false);
if (isempty(sfo2)),
def{4} = '0.2*2.56e6';
end;
if (isforcetaper),
def{7} = 'true';
else
def{7} = 'false';
end;
vals = inputdlg(prompt,'Simulation constants',1,def);
vals = cellfun(@eval,vals,'UniformOutput',false);
[freq,viscosity,sfo,sfo2,ps,gridres,isforcetaper] = vals{:};
putvar(filenameopt{:}, 'freq','viscosity','sfo','sfo2','ps','gridres','isforcetaper');
end;
nfr = size(xm,2);
npt = size(xm,1);
s0 = [zeros(1,nfr); cumsum(sqrt(diff(xm).^2 + diff(ym).^2))];
s = nanmean(s0,2);
istether = false;
disp(' Estimating com speed...');
if (all(abs(xm(1,:) - xm(1,1)) < 1e-3))
disp(' -> appears to be a tethered head simulation');
istether = true;
comspeed = zeros(size(t));
if (isempty(opt.samraibasedir))
disp(' ... cannot get flow speed without samrai dirs');
flowspeed = 0;
else
samraidirs = getdirectorynames(fullfile(opt.samraibasedir,'visit*'))';
[x,y,V] = importsamrai(samraidirs{2},'vars',{'U_0','U_1'}, ...
'interpolaten',[100 50]);
flowspeed = mean(V.U_0(x < xm(1,1)-1));
end;
end;
[width,area,sn, comx,comy,comvelx,comvely] = ...
estcomspeed(t,xm,ym,xn,yn,xl,xr,yl,yr);
if (isforcetaper),
forcetaper = width(:,1) ./ max(width(:,1));
else
forcetaper = ones(npt,1);
end;
if (~istether)
comspeed = sqrt(comvelx.^2 + comvely.^2);
%unit vector pointing in the direction of the swimming speed, as a cubic
%spline in 3 parts, which should get rid of any fluctuation at the level of
%the tail beat frequency
dt = t(2) - t(1);
dur = round(2/dt); %smooth over 2 sec
comxsm = runavg(comx, dur);
comysm = runavg(comy, dur);
swimvecx = deriv(t,comxsm);
swimvecy = deriv(t,comysm);
mag = sqrt(swimvecx.^2 + swimvecy.^2);
swimvecx = swimvecx ./ mag;
swimvecy = swimvecy ./ mag;
else
swimvecx = -1 * ones(size(t));
swimvecy = zeros(size(t));
end;
%now average speeds over cycles to look for "steady"
%define cycles
cycle = t * freq;
cycle = cycle - min(floor(cycle));
cyclenum = floor(cycle)+1;
cyclenum2 = floor(cycle*2)+1;
disp(' Looking for steady speed...');
if (istether)
ncycle = max(cyclenum);
dt = t(2) - t(1);
cycleindlen = round(1/freq/dt);
k = 1:length(t)-cycleindlen;
dX = NaN(size(t));
dX(k+cycleindlen) = mean(sqrt((xm(:,k+cycleindlen) - xm(:,k)).^2 + ...
(ym(:,k+cycleindlen) - ym(:,k)).^2));
dXbycycle = accumarray(cyclenum(:), dX(:), [], @nanmean);
steadycycle = length(dXbycycle) - 1;
while ((steadycycle >= 1) && all(dXbycycle(steadycycle:end) < opt.steadydX))
steadycycle = steadycycle-1;
end;
else
%average comspeed in each cycle
comspeedbycycle = accumarray(cyclenum(:), comspeed(:), [], @nanmean);
%and the amount it changes, relative to the current value
dcomspeed = diff(comspeedbycycle) ./ comspeedbycycle(1:end-1);
%look for those cycles that change less than opt.steadythresh
steadycycle = length(comspeedbycycle)-1;
while ((steadycycle >= 1) && all(dcomspeed(steadycycle:end) < opt.steadythresh)),
steadycycle = steadycycle-1;
end;
end;
if (steadycycle == 1)
steadycycle = 2;
end
issteady = (cyclenum >= steadycycle);
%amplitude = displacement relative to the center of mass, perpendicular to the swimming
%vector
ampcont = -(xm - comx(ones(npt,1),:)) .* swimvecy(ones(npt,1),:) + ...
(ym - comy(ones(npt,1),:)) .* swimvecx(ones(npt,1),:);
ampsteady = nanmean(range(ampcont(:,issteady)));
goodamp = issteady | (range(ampcont) < 2*ampsteady);
ampcont(:,~goodamp) = NaN;
%track curvature waves
%no smoothing in curvature, because we've already smoothed
disp(' Estimating curvature...');
curve = curvature(xm,ym, 'discrete','smooth',opt.curvesmoothcutoff);
%track zero crossings in curvature
disp(' Tracking curvature zero crossings...');
[indzero0,sgnzero0] = ...
analyzeKinematics(s,t,xm,ym, 'curve',curve, 'nsmoothcurve',0, ...
'zeros', 'backwnd',0.5, 'returnpeaksign');
%track peaks in amplitude envelope
disp(' Tracking amplitude peaks...');
[indpeak0,sgnpeak0,~,~,~,~,~,wavespeed0,wavelen0,~,waven0] = ...
analyzeKinematics(s,t,xm,ym, 'curve',ampcont, 'nsmoothcurve',10, ...
'peaks','backwnd',0.5, 'returnpeaksign');
%also track the activation wave
disp(' Finding the activation wave...');
[indact,indactoff,isactleft] = findactivationwave(actl,actr);
actlen = NaN(size(indact));
for j = 1:size(indact,2)-1,
for i = 1:npt,
if (isfinite(indact(i,j))),
next = last(indact(:,j+1) <= indact(i,j));
if (~isempty(next)),
actlen(i,j) = 2*(s(i)-s(next));
end;
end;
end;
end;
tact = NaN(size(indact));
good = isfinite(indact);
tact(good) = t(indact(good));
actspeed = NaN(1,size(tact,2));
for i = 1:length(actspeed),
good = isfinite(tact(:,i));
if (sum(good) > 100),
p = polyfit(tact(good,i),s(good), 1);
actspeed(i) = p(1);
end;
end;
%early cycles are those with more than three activation starts on frame 1
early = sum(indact == 1) > 3;
firstright = first(~isactleft & ~early);
t0 = t(first(isfinite(indact(:,firstright))));
%match up the curvature to the activation
disp(' Aligning curvature and amplitude peaks to activation wave...');
cyclematchzero = zeros(1,size(indact,2));
cyclematchpeak = zeros(1,size(indact,2));
numincyclezero = zeros(1,size(indact,2));
numincyclepeak = zeros(1,size(indact,2));
for i = 1:size(indact,2),
indact1 = first(indact(:,i),isfinite(indact(:,i)));
indact2 = last(indactoff(:,i),isfinite(indactoff(:,i)));
if (isactleft(i)),
sgn1 = opt.leftsidecurvature;
else
sgn1 = -opt.leftsidecurvature;
end;
numincycle1 = sum((indzero0 >= indact1) & (indzero0 <= indact2));
numincycle1(sgnzero0 ~= sgn1) = 0;
[n1,a] = max(numincycle1);
cyclematchzero(i) = a;
numincyclezero(i) = n1;
if (isactleft(i)),
%NB: we want left side activation to correspond to peak right side
%excursion, because that's appx when the left side muscle is
%*shortest*
sgn1 = -opt.leftsidepeak;
else
sgn1 = opt.leftsidepeak;
end;
numincycle1 = sum((indpeak0 >= indact1) & (indpeak0 <= indact2));
numincycle1(sgnpeak0 ~= sgn1) = 0;
[n1,a] = max(numincycle1);
cyclematchpeak(i) = a;
numincyclepeak(i) = n1;
end;
for i = 1:size(indzero0,2),
k = find(cyclematchzero == i);
if (length(k) > 1),
[~,a] = max(numincyclezero(k));
cyclematchzero(k) = 0;
cyclematchzero(k(a)) = i;
end;
end;
for i = 1:size(indpeak0,2),
k = find(cyclematchpeak == i);
if (length(k) > 1),
[~,a] = max(numincyclepeak(k));
cyclematchpeak(k) = 0;
cyclematchpeak(k(a)) = i;
end;
end;
%rearrange data to match the activation waves
indzero = NaN(size(indact));
good = cyclematchzero ~= 0;
indzero(:,good) = indzero0(:,cyclematchzero(good));
sgnzero = NaN(1,size(indact,2));
sgnzero(:,good) = sgnzero0(:,cyclematchzero(good));
indpeak = NaN(size(indact));
good = cyclematchpeak ~= 0;
indpeak(:,good) = indpeak0(:,cyclematchpeak(good));
sgnpeak = NaN(1,size(indact,2));
sgnpeak(good) = sgnpeak0(cyclematchpeak(good));
%find the peaks of curvature
disp(' Looking for curvature peaks...');
indpeakcurve = NaN(size(indzero));
sgnpeakcurve = NaN(size(indzero));
for j = 1:size(indzero,2)-1,
for i = 1:size(indzero,1),
if (~isnan(indzero(i,j)) && ~isnan(indzero(i,j+1)) && ...
(indzero(i,j+1) > indzero(i,j))),
k = indzero(i,j):indzero(i,j+1);
curve1 = curve(i,k);
mx = max(abs(curve1));
ishigh = abs(curve1) >= opt.pkthresh*mx;
sgn1 = sign(first(curve1,ishigh));
if (any(sign(curve1(ishigh)) ~= sgn1)),
ctr = NaN;
else
weight = abs(curve1(ishigh));
if (length(weight) > 1),
weight = (weight - min(weight))/range(weight);
else
weight = 1;
end;
ctr = sum(k(ishigh) .* weight) ./ ...
sum(weight);
end;
indpeakcurve(i,j) = round(ctr);
sgnpeakcurve(i,j) = sgn1;
end;
end;
end;
good = cyclematchpeak ~= 0;
wavespeed = NaN(1,size(indzero,2));
wavespeed(good) = wavespeed0(cyclematchpeak(good));
waven = zeros(1,size(indzero,2));
waven(good) = waven0(cyclematchpeak(good));
wavelen = NaN(size(indzero));
wavelen(:,good) = wavelen0(:,cyclematchpeak(good));
amp = NaN(size(indact));
for c = 1:size(indact,2)-2,
if any((cyclenum2 == c) | (cyclenum2 == c+1))
amp(:,c) = range(ampcont(:,(cyclenum2 == c) | (cyclenum2 == c+1)),2)/2;
end
end;
disp(' Calculating work loops...');
[lennorm,worktot,workpos,workneg,workposact,worknegact] = workloop(t, xl,yl,fmusPl,actl, ...
xr,yr,fmusPr,actr, ...
'per',1/freq, 'plot',false, 'forcetaper',forcetaper);
disp(' Calculating fluid forces...');
Force = fluidforces(t,freq, swimvecx,swimvecy, xm,ym, fxmtot,fymtot, ...
xl,yl,fxltot,fyltot, xr,yr,fxrtot,fyrtot);
out.freq = freq;
out.viscosity = viscosity;
out.sfo = sfo;
out.sfo2 = sfo2;
out.ps = ps;
out.gridres = gridres;
out.isforcetaper = isforcetaper;
out.t = t;
out.s = s;
out.s0 = s0;
out.sn = sn;
out.nfr = nfr;
out.npt = npt;
out.comx = comx;
out.comy = comy;
out.comvelx = comvelx;
out.comvely = comvely;
out.swimvecx = swimvecx;
out.swimvecy = swimvecy;
out.comspeed = comspeed;
out.width = width;
out.area = area;
out.curve = curve;
out.ampcont = ampcont;
out.amp = amp;
out.wavespeed = wavespeed;
out.wavelen = wavelen;
out.indact = indact;
out.indactoff = indactoff;
out.isactleft = isactleft;
out.actspeed = actspeed;
out.actlen = actlen;
out.indzero = indzero;
out.sgnzero = sgnzero;
out.indpeak = indpeak;
out.sgnpeak = sgnpeak;
out.indpeakcurve = indpeakcurve;
out.sgnpeakcurve = sgnpeakcurve;
out.issteady = issteady;
out.steadycycle = steadycycle;
out.cyclenum = cyclenum;
out.lennorm = lennorm;
out.worktot = worktot;
out.workpos = workpos;
out.workneg = workneg;
out.workposact = workposact;
out.worknegact = worknegact;
out.Force = Force;
out.HGREV = savehgrev([], 'datafile',datafilename);
if (~isempty(opt.samraibasedir) && inputyn('Load fluid data? '))
disp(' Calculating fluid quantities...');
samraidirs = getdirectorynames(fullfile(opt.samraibasedir,'visit*'))';
if (isempty(samraidirs))
saveextra = {};
else
if (~isempty(opt.outfile))
[pn,fn,ext] = fileparts(opt.outfile);
cont = fullfile(pn,[fn 'Continue.mat']);
else
cont = '';
end;
if (~isempty(cont) && exist(cont,'file'))
load(cont, 'Stress','samraidirs','fr','Energy');
fr0 = fr;
fprintf('Continuing from frame %d...\n', fr0);
else
fr0 = 1;
end;
boundx0 = [xm(1,:); xl(2:end-1,:); xm(end,:); xr(end-1:-1:2,:); xm(1,:)];
boundy0 = [ym(1,:); yl(2:end-1,:); ym(end,:); yr(end-1:-1:2,:); ym(1,:)];
boundu0 = [um(1,:); ul(2:end-1,:); um(end,:); ur(end-1:-1:2,:); um(1,:)];
boundv0 = [vm(1,:); vl(2:end-1,:); vm(end,:); vr(end-1:-1:2,:); vm(1,:)];
Energy.totalke = NaN(1,nfr);
Energy.dissip = NaN(1,nfr);
Energy.boundflux = NaN(4,nfr);
opt1.rho = 1; % in g/cm^3
opt1.mu = viscosity;
opt1.savepressure = opt.savepressure;
opt1.savevorticity = opt.savevorticity;
N = min(length(samraidirs)-1, nfr);
for fr = fr0:N,
fprintf('Importing %s (%d%%)...\n', samraidirs{fr+1}, round((fr+1)/nfr*100));
V = importsamrai(samraidirs{fr+1},'vars',{'U_0','U_1','P'});
V = getsamraipatchedges(V);
V = velderivsamrai(V);
[totalke1,dissip1,boundflux1] = energybalance1(V,opt1);
Energy.totalke(fr) = totalke1;
Energy.dissip(fr) = dissip1;
Energy.boundflux(:,fr) = boundflux1;
S1 = fluidstressnearboundary1(V, boundx0(:,fr),boundy0(:,fr),...
boundu0(:,fr),boundv0(:,fr), opt1);
Stress.tanx{fr} = S1.tanx;
Stress.tany{fr} = S1.tany;
Stress.s{fr} = S1.s;
Stress.n{fr} = S1.n;
Stress.nearboundx{fr} = S1.nearboundx;
Stress.nearboundy{fr} = S1.nearboundy;
Stress.normstress{fr} = S1.normstress;
Stress.tanstress{fr} = S1.tanstress;
if (opt.savepressure)
Stress.nearboundp{fr} = S1.nearboundp;
end;
if (opt.savevorticity)
Stress.nearboundut{fr} = S1.nearboundut;
Stress.nearboundun{fr} = S1.nearboundun;
Stress.vorticity{fr} = S1.vorticity;
end;
if (~isempty(cont) && (mod(fr,10) == 0))
save(cont,'Stress','samraidirs','fr','Energy');
end;
end;
out.Energy = Energy;
out.Stress = Stress;
end;
end;
if (istether)
out.flowspeed = flowspeed;
end;
disp(' Saving data...');
if (~isempty(opt.outfile)),
save(opt.outfile, '-struct','out');
else
putvar(filenameopt{:}, '-fromstruct','out', '-all');
end;
|
classdef neighbourhood < handle
properties
label
m % row
n % column
end
properties (Transient)
n_selfneighs
end
methods
function obj = neighbourhood(m, n, varargin)
if nargin<1
obj.m = 1;
obj.n = 1;
else
obj.m = m;
obj.n = n;
end
end
function obj = uplus(obj1)
obj = utils.uplus(obj1);
end
function set_n_selfneighs(obj)
obj.n_selfneighs = ones(obj.m*obj.n,1); % preset so as to normalize to one in the next function
% count size of neighbourhood of each node
obj.n_selfneighs = obj.neigh_avg(ones(obj.m*obj.n,1));
end
function neigh_avg(obj, state)
% if m or n were changed in the meantime, update n_selfneighs
if ~isequal(size(state),size(obj.n_selfneighs))
obj.set_n_selfneighs();
end
end
end
methods(Static)
function [m, n] = get_m_n(k, m_seed, n_seed)
if nargin<2; m_seed = 1; n_seed = 1; end
if m_seed<n_seed
m = m_seed*2^ceil((k-1)/2); n = n_seed*2^floor((k-1)/2);
else
m = m_seed*2^floor((k-1)/2); n = n_seed*2^ceil((k-1)/2);
end
end
function [m, n] = get_m_n_N(N)
for m=floor(sqrt(N)):-1:1
if mod(N,m)==0; break; end
end
n = N/m;
end
end
end
|
%Nhom 1
%53
%Pham Ba Tung
%B15DCDT221
I0=imread('chuoi.jpg');
size(I0)
subplot(2,2,1 )
imshow(I0)
I=rgb2gray(I0);
I1=im2bw(I0);
subplot(2,2,2)
imshow(I)
subplot(2,2,3)
imshow(I1)
[n m] = size(I);
T = 128;
for i=1:n
for j=1:m
if I(i,j) < T
I(i,j) = 0;
if j<m
I(i,j+1) = I(i,j);
end
else
e = 255 - I(i,j);
I(i,j) = 255;
if j<m
I(i,j+1) = e;
end
end
end
end
subplot(2,2,4)
imshow(I)
|
function tokenList = split(str, delimiter)
% SPLIT Split a string based on a given delimiter
% Usage:
% tokenList = split(str, delimiter)
% Roger Jang, 20010324
tokenList = {};
remain = str;
i = 1;
while ~isempty(remain),
[token, remain] = strtok(remain, delimiter);
tokenList{i} = token;
i = i+1;
end
|
% CLASSIFYRBFN Classify data with radial basis function network.
% OUT = CLASSIFYRBFN(X,MODEL) classifies the data in X (N samples-by-D
% features) by using a radial basis function network (RBFN), where MODEL is
% a structure with the RBFN parameters: centroids, spreads, and weights.
% OUT is a structure with both the scores obtained from output units and the
% class labels assigned to each sample in X. If OUT.Labels=1 is a benign lesion,
% whereas if OUT.Labels=2 is a malignant lesion
%
% Example:
% -------
% load('bcwd.mat');
% ho = crossvalind('HoldOut',Y,0.2); % Hold-out 80-20%
% [Xtr,m,s] = softmaxnorm(X(ho,:)); % Training data normalization
% Xtt = softmaxnorm(X(~ho,:),[m;s]); % Test data normalization
% Ytr = Y(ho,:); % Training targets
% Ytt = Y(~ho,:); % Test targets
% Model = trainRBFN(Xtr,Ytr); % Train RBFN
% Out = classifyRBFN(Xtt,Model); % Test RBFN
% perf = classperf(Out.Labels,Ytt); % Evaluate classification performance
%
% See also AUC CLASSPERF CLASSIFYLDA CLASSIFYSVM CLASSIFYLSVM CLASSIFYRF
%
%
% References:
% ----------
% Theodoridis S, Koutroumbas K. Pattern recognition. 4th edition.
% Burlington, MA: Academic Press 2009.
%
% K. L. Priddy, P. E. Keller, Artificial Neural Networks: An Introduction.
% Bellingham, WA: SPIE-The Int. Soc. Optical Eng., 2005.
% ------------------------------------------------------------------------
% Cinvestav-IPN (Mexico) - LUS/PEB/COPPE/UFRJ (Brazil)
% CLASSIFYRBFN Version 1.0 (Matlab R2014a Unix)
% November 2016
% Copyright (c) 2016, Wilfrido Gomez Flores
% ------------------------------------------------------------------------
function Out = classifyRBFN(Xtt,Model)
% Load model
Ci = Model.Centroids;
Si = Model.Sigmas;
W = Model.Weights;
% Classify
Ntt = size(Xtt,1);
DV = eucdist(Xtt,Ci);
S = Si(ones(Ntt,1),:);
aux2 = exp(-DV./(2*S.^2));
phi2 = cat(2,ones(Ntt,1),aux2);
Out.Scores = phi2*W;
[~,Out.Labels] = max(Out.Scores,[],2);
%*******************************************************************
function D = eucdist(A,B)
nA = sum(A.*A,2);
nB = sum(B.*B,2);
D = abs(bsxfun(@plus,nA,nB') - 2*(A*B'));
|
% this function is to calcaluate and draw 2 dimensional histogram.
function samples = twoDbin
load PTsampleing.mat;
X = chain(:,1);
Y = chain(:,2);
xbins = -1.5:1:1.5;
% xbins(find(xbins==0))=[];
ybins = -1.5:1:1.5;
% ybins(find(ybins==0))=[];
xNumBins = numel(xbins);
yNumBins = numel(ybins);
Xi = round(interp1(xbins,1:xNumBins,X,'linear','extrap'));
Yi = round(interp1(ybins,1:yNumBins,Y,'linear','extrap'));
Xi = max( min(Xi,xNumBins), 1);
Yi = max( min(Yi,yNumBins), 1);
H = accumarray([Yi(:) Xi(:)],1,[yNumBins xNumBins]);
%figure
%imagesc(xbins, ybins, H), axis on %# axis image
%colormap hot; colorbar
%hold on, plot(X, Y,'b.','MarkerSize',1), hold off
H(2,:) = H(2,:)+H(3,:);
H(3,:) = [];
H(:,2) = H(:,2)+H(:,3);
H(:,3) =[]
samples = reshape(H,1,[]);
samples = samples/sum(samples);
return;
clear
|
function [Vstart,Vstop,Xstart,Xstop] = create_goal(fig)
cmap = lines(5);
F = [1 2 3 4;
5 6 7 8;
1 2 6 5;
2 3 7 6;
3 4 8 7;
1 4 8 5];
% Start
x = 130;
y = 300;
z = 20;
w = 20;
h = 20;
Vx_start = [x x+w x+w x x x+w x+w x];
Vy_start = [y y y+h y+h y y y+h y+h];
Vz_start = [0 0 0 0 z z z z];
Vstart = [Vx_start' Vy_start' Vz_start'];
Xstart = [x+w/2 y+h/2 z/2 0 0 0]';
x = 250;
y = 100;
w = 20;
h = 20;
z = 20;
Vx_stop = [x x+w x+w x x x+w x+w x];
Vy_stop = [y y y+h y+h y y y+h y+h];
Vz_stop = [0 0 0 0 z z z z];
Vstop = [Vx_stop' Vy_stop' Vz_stop'];
Xstop = [x+w/2 y+h/2 z/2 0 0 0];
if ~isempty(fig)
figure(fig);
hold on;
patch('Faces',F,'Vertices',Vstart,'FaceColor','None','EdgeColor',cmap(5,:));
patch('Faces',F(1,:),'Vertices',Vstart(1:4,:),'FaceColor',cmap(5,:),'FaceAlpha',0.5);
plot3(Xstart(1),Xstart(2),Xstart(3),'*g','MarkerSize',15,'Linewidth',2);
patch('Faces',F,'Vertices',Vstop,'FaceColor','None','EdgeColor',cmap(2,:));
patch('Faces',F(1,:),'Vertices',Vstop(1:4,:),'FaceColor',cmap(2,:),'FaceAlpha',0.5);
end
end
|
% Enhances the contrast of the image
% Adapted from http://imageprocessingblog.com/histogram-adjustments-in-matlab-part-i/
function [out] = enhance_contrast(im)
hsvimg = rgb2hsv(im);
for ch=2:3
hsvimg(:,:,ch) = imadjust(hsvimg(:,:,ch), ...
stretchlim(hsvimg(:,:,ch), 0.01));
end
out = hsv2rgb(hsvimg);
end
|
clc
clear all
close all
%
% a=input('Enter the Choice')
disp('This is a MASK of Median Filter')
q1=input('Enter the size of Mask ')
g1=[1 1 1;1 1 1;1 1 1]
subplot(2,2,3)
imshow(g1,[])
title('This is Mask')
a1=imread('cameraman.tif');
subplot(2,2,1)
a11=double(a1);
imshow(a1)
title('Original image')
[r,c] = size(a11);
a2= imnoise(a1,'salt & pepper',0.02);
subplot(2,2,2)
imshow(a2)
title('Input Image with Salt and Pepper Noise')
NIm=zeros(r,c);
t=(q1-1)/2;
xc=t+1;
q2=((q1+1)/2)-1
for i=xc:r-1
for j=xc:c-1
temp=0;
for k=-t:t
for l=-t:t
temp(i,j)=(a2(k+i,l+j).*g1(k+xc,l+xc));
temp2(k+2,l+2)=(temp(i,j));
temp3=temp2(:);
temp4=sort(temp3');
temp5=temp4(ceil(end/2));
NIm(i+q2-1,j+q2-1)=temp5;
end
end
end
end
subplot(2,2,4)
imshow(NIm,[])
title('Output Image')
|
%% Params
verbose = 0;
use_interval = true;
solvers = {'mosek' 'mosek_INTPNT_ONLY' 'sedumi' 'sdpt3'};
basis = 'CG_red';
slack = 'slack(z=x+t-1)'; slackcode = 3;
%slack = 'slack(z=x-t)'; slackcode = 1;
nout = 5;
dist_A = low2high_dist('W-type', nout, use_interval, 0);%infea
dist_B = low2high_dist('uniform', nout, use_interval, 0);%fea
%dist_A = [];dist_B = [];
%start_point = 0.035;
%stop_point = 0.045;
%start_point = 0.05276;
%stop_point = 0.05277;
%start_point = 0.3333333;
%stop_point = 0.33333336;
start_point = 0.065;stop_point = 0.075;
%start_point = 0.0573;stop_point = 0.05732;%nout4
%start_point = 0.057352;stop_point = 0.057353;%nout3
steps = 10;
%% I/O
dt = datestr(datetime('now'), 'mmm-dd-yyyy_HH.MM');
results_path = sprintf('results/slack%d_%s_%s.mat', slackcode, basis, dt);
data = struct();
data.start_point = start_point; data.stop_point = stop_point;
data.steps = steps; data.nout = nout; data.basis = basis;
data.slack = slack;
%% Trials
for solver = solvers
lbs =calc_lbound(nout, dist_A, dist_B, solver{1}, basis, slack, start_point, stop_point, steps, verbose, use_interval);
if slackcode == 3
data.([solver{1} '_lbs']) = lbs - 1;
else
data.([solver{1} '_lbs']) = lbs;
end
end
save(results_path, 'data');
%% Call plotting function
lb_plot(results_path);
|
function [ numfluxSolver, surfluxSolver, volumefluxSolver ] = initFluxSolver( obj )
%INITNUMFLUXSOLVER Summary of this function goes here
% Detailed explanation goes here
if obj.option.isKey('NumFluxType')
if obj.option.isKey('nonhydrostaticType')
if obj.getOption('NumFluxType') == enumSWENumFlux.HLL &&...
obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic
% Numerical flux type pointed and non-hydrostatic type pointed
numfluxSolver = SWEHLLNumFluxSolver1d( );
surfluxSolver = SWEFaceFluxSolver1d( );
% LF and Roe flux to be added
elseif obj.getOption('NumFluxType') == enumSWENumFlux.HLL &&...
obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Nonhydrostatic
numfluxSolver = SWENonhydroHLLNumFluxSolver1d( );
surfluxSolver = SWENonhydroFaceFluxSolver1d( );
% LF and Roe flux to be added
end
else % No nonhydrostatic type pointed, and hydrostatic by default
if obj.getOption('NumFluxType') == enumSWENumFlux.HLL
numfluxSolver = SWEHLLNumFluxSolver1d( );
surfluxSolver = SWEFaceFluxSolver1d( );
% LF and Roe flux to be added
end
end
else % No numerical flux type pointed
if obj.option.isKey('nonhydrostaticType')
if obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic
numfluxSolver = SWEHLLNumFluxSolver1d( );
surfluxSolver = SWEFaceFluxSolver1d( );
elseif obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Nonhydrostatic
numfluxSolver = SWENonhydroHLLNumFluxSolver1d( );
surfluxSolver = SWENonhydroFaceFluxSolver1d( );
end
else % No nonhydrostatic type pointed, and hydrostatic by default
numfluxSolver = SWEHLLNumFluxSolver1d( );
surfluxSolver = SWEFaceFluxSolver1d( );
end
end
parent = metaclass(obj);
if strcmp(parent.SuperclassList.Name, 'SWEConventional1d')
if obj.option.isKey('nonhydrostaticType')
if obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic
volumefluxSolver = SWEVolumeFluxSolver1d();
else
volumefluxSolver = SWENonhydroVolumeFluxSolver1d();
end
else
volumefluxSolver = SWEVolumeFluxSolver1d();
end
elseif strcmp(parent.SuperclassList.Name, 'SWEPreBlanaced1d') % SWEPreBlanaced1d
if obj.option.isKey('nonhydrostaticType')
if obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic
volumefluxSolver = SWEPrebalanceVolumeFlux1d();
else
volumefluxSolver = SWENonhydroPrebalanceVolumeFluxSolver1d();
end
else
volumefluxSolver = SWEPrebalanceVolumeFlux1d();
end
elseif strcmp(parent.SuperclassList.Name, 'SWEWD1d')
if obj.option.isKey('nonhydrostaticType')
if obj.getOption('nonhydrostaticType') == enumNonhydrostaticType.Hydrostatic
volumefluxSolver = SWEWDVolumeFlux1d();
else
volumefluxSolver = SWENonhydroWDVolumeFluxSolver1d();
end
else
volumefluxSolver = SWEWDVolumeFlux1d();
end
end
end
|
function [ vwillr ] = percentr( vtime,vhigh,vlow,vclose,len )
%PERCENTR 计算willr,根据mc
% version 1.0 , luhuaibao, 2013.9.27
[~,id] = sort( -vtime );
% 最近的排在上面
vhigh = vhigh(id);
vlow = vlow(id);
vclose = vclose(id);
var0 = max( vhigh(1:len ) );
var1 = var0 - min( vlow(1:len) ) ;
if var1 ~= 0
vwillr = 100 - ( ( var0 - vclose(1) ) / var1 ) * 100 ;
else
vwillr = 0 ;
end
end
|
clear, clc
xrng = [100 1000];
yrng = [-350 350];
xdiv = 40;
ydiv = 40; % number of x/y divisions
hbins = linspace(xrng(1), xrng(2), xdiv);
vbins = linspace(yrng(1), yrng(2), xdiv);
frmat = zeros(xdiv, ydiv);
frtrls = zeros(xdiv, ydiv);
targetdir = 'C:\Users\Hrishikesh\Data\krPTBData\';
[filename pathname] = uigetfile([targetdir 'S3*.mat'], 'Load Exp Session File (not sp2)', 'MultiSelect', 'on');
fullpathname = strcat(pathname, filename); % all the files in pathname
%% Because I want to combine files and build up the firing rate plots
if iscell(fullpathname)
numfiles = length(fullpathname);
else
numfiles = 1;
end
hasPrintedOnce = false;
allwindow = 0.02:0.01:0.2;
for wi = 1:length(allwindow) % time back
window = allwindow(wi);
for dt = 1:numfiles
if iscell(fullpathname)
thisfilename = fullpathname{dt};
rawname = filename{dt};
else
thisfilename = fullpathname;
rawname = filename;
end
% first load the session file
load(thisfilename) % this has the locs and successes
load(strcat(thisfilename(1:end-4), '_sp2.mat'))
eval(['eyeh = ' rawname(1:end-4) '_Ch3.values;'])
eval(['eyev = ' rawname(1:end-4) '_Ch4.values;'])
eval(['trig = ' rawname(1:end-4) '_Ch5.values;'])
eval(['trigTS = ' rawname(1:end-4) '_Ch5.times;'])
eval(['photo = ' rawname(1:end-4) '_Ch6.values;'])
eval(['photoTS = ' rawname(1:end-4) '_Ch6.times;'])
eval(['Allspktimes = ' rawname(1:end-4) '_Ch7.times;'])
eval(['spkcodes = ' rawname(1:end-4) '_Ch7.codes;'])
eval(['eyeSamplingRate = ' rawname(1:end-4) '_Ch3.interval;'])
numIdx1sec = round(1/eyeSamplingRate);
%numIdxLittlePost = round(0.5/eyeSamplingRate);
clus = 1;
spktimes = Allspktimes(spkcodes(:,1) == clus); %seconds
if ~hasPrintedOnce, fprintf('Num Clusters: %i, Cluster Plotted: %i \n', length(unique(spkcodes(:,1))), clus), end
%% Get data (bookkeeping)
% smooth out the photocell
idxPhoto = photo > 0.05;
photo(idxPhoto) = 0.3;
photo(~idxPhoto) = 0;
dphoto = diff(photo);
dphoto = [0; dphoto]; % to take care of the indexing issue
idxOn = find(dphoto == 0.3); % photocell on
idxOff = find(dphoto == -0.3);
% note, the first one will be due to the PTB syncing routine
idxOn(1) = [];
idxOff(1) = [];
% - also importantly, note that the times that the photo is on/off
% photoTS(idxOn(i)) or photoTS(idxOff(i))
% smooth out triggers
idxTrig = trig > 0.1;
trig(idxTrig) = 0.5;
trig(~idxTrig) = 0;
dTrig = diff(trig);
dTrig = [0; dTrig];
idxTstart = find(dTrig == 0.5);
idxTstop = find(dTrig == -0.5);
%% just find when the flashes happened in the "storeSuccess" lists
timeFlashesStarts = [];
timeFlashesEnds = [];
nonzeroidx = find(storeSuccess);
for ti = 1:length(find(storeSuccess))
trl = storeSuccess(nonzeroidx(ti));
thisIndFlashes = find(idxOn > idxTstart(trl) & idxOn < idxTstop(trl));
thisNumFlashes = length(thisIndFlashes);
if thisNumFlashes == 5
tflashes = nan(10,1);
tflashes([1,3,5,7,9]) = photoTS(idxOn(thisIndFlashes));
tflashes([2,4,6,8,10]) = photoTS(idxOff(thisIndFlashes));
timeFlashesStarts(end+1:end+10,1) = tflashes;
tflashes = nan(10,1);
tflashes([1,3,5,7,9]) = photoTS(idxOff(thisIndFlashes));
tflashes([2,4,6,8]) = photoTS(idxOn(thisIndFlashes(2:end)));
tflashes(10) = tflashes(9)+nanmean(diff(tflashes));
timeFlashesEnds(end+1:end+10,1) = tflashes;
else
fprintf('Possible Error with Trial: %i. Num flashes = %i. \n', trl, thisNumFlashes)
storeSuccess(ti) = 0;
end
end
if ~hasPrintedOnce, fprintf('Num Flashes Detected: %i. Num storeXlocs: %i. \n', length(timeFlashesStarts), length(storeXlocs)); hasPrintedOnce = true; end
%% find every spike and determine what the frame was some time before it
% screen resolution 1024x768
ycent = 384;
% the yaxis is flipped
storeYlocs = -(storeYlocs - ycent);
numavgs = 1;
for spi = 1:length(spktimes)
thisspiketime = spktimes(spi) - window;
idxFS = find(timeFlashesStarts < thisspiketime, 1, 'last');
if ~isempty(idxFS) && timeFlashesStarts(idxFS) < thisspiketime && timeFlashesEnds(idxFS) > thisspiketime
frmat = frmat.*numavgs;
for nf = 1:size(storeXlocs,2) % find out which row/col it goes into and add the appropriate value
row = find(hbins > storeXlocs(idxFS,nf), 1, 'first');
col = find(vbins > storeYlocs(idxFS,nf), 1, 'first');
% add 1 to the location of where the stimulus was
frmat(row,col) = frmat(row,col) + 1;
end% nf
% recompute average
numavgs = numavgs + 1;
frmat = frmat./numavgs;
end
end
end
clf, hold on
figure(1), heatmap(frmat'); % the data is averaged on the go
axis([0.5 xdiv 0.5 ydiv])
title(['Time Back: ' num2str(allwindow(wi))])
colorbar
ax = axis;
line(ax(1:2),[mean(ax(3:4)) mean(ax(3:4))], 'LineStyle', '--','LineWidth', 2, 'Color', 'k')
line([mean(ax(1:2)) mean(ax(1:2))], ax(3:4), 'LineStyle', '--','LineWidth', 2, 'Color', 'k')
drawnow
end
|
% Extract pixel pairs from both HSI and RGB images manually and let the
% algorithm to pick up some random pixels for manifold alignment.
if ~exist('hsiToRgbManifoldDatasetGen', 'var')
hsiToRgbManifoldDatasetGen = false;
end
if hsiToRgbManifoldDatasetGen
fb_HSI_Image = RotateHsiImage(hsiCubeData.DataCube, -90);
rgbFromHsi = ConstructRgbImage(fb_HSI_Image, 2, 3, 4);
else
fb_HSI_Image = RotateHsiImage(reflectanceCube.DataCube, -90);
rgbFromHsi = GetTriBandRgbImage(fb_HSI_Image);
end
classesInHsi = 7;
noOfSample = 10;
% Positions in [height, width] format.
extractedHsiPixels = zeros(noOfSample * classesInHsi, 2);
extractedHsiVector = zeros(noOfSample, 2);
extractedRgbPixels = zeros(noOfSample * classesInHsi, 2);
extractedRgbVector = zeros(noOfSample, 2);
for nId = 1: classesInHsi
[topLeft, btmRight] = PickUpPixelArea(rgbFromHsi);
H = (btmRight(1) - topLeft(1));
W = (btmRight(2) - topLeft(2));
totalSamples = H * W;
coordList = zeros(totalSamples, 2);
for nX = 1:H
for nY = 1:W
coordList(((nX - 1) * W) + nY, :) = [(topLeft(1) - 1) + nX, (topLeft(2) - 1) + nY];
end
end
% Randomize the data and pick n number of samples.
randIds = randperm(totalSamples);
for px = 1: noOfSample
extractedHsiVector(px, :) = coordList(randIds(px), :);
end
extractedHsiPixels((((nId - 1) * noOfSample) + 1): (((nId - 1) * noOfSample) + noOfSample), :) = extractedHsiVector(:,:);
% end
%% RGB
% Positions in [height, width] format.
% for nId = 1: classesInHsi
[topLeft, btmRight] = PickUpPixelArea(higResRgb);
H = (btmRight(1) - topLeft(1));
W = (btmRight(2) - topLeft(2));
totalSamples = H * W;
coordList = zeros(totalSamples, 2);
for nX = 1:H
for nY = 1:W
coordList(((nX - 1) * W) + nY, :) = [(topLeft(1) - 1) + nX, (topLeft(2) - 1) + nY];
end
end
% Randomize the data and pick n number of samples.
randIds = randperm(totalSamples);
for px = 1: noOfSample
extractedRgbVector(px, :) = coordList(randIds(px), :);
end
extractedRgbPixels((((nId - 1) * noOfSample) + 1): (((nId - 1) * noOfSample) + noOfSample), :) = extractedRgbVector(:,:);
close all;
end
%% Clear variables
vars = {'noOfSample', 'nId', 'btmRight', 'classesInHsi', 'coordList',...
'randIds', 'px', 'nX', 'nY', 'H', 'W', 'topLeft', 'totalSamples'};
clear(vars{:});
|
function [ out ] = nonan_Image( img )
out = zeros(size(img));
for k=1:size(img,3)
for i=1:size(img,1)
for j=1:size(img,2)
if ( isnan(img(i,j,k))) out(i,j,k)=0;
else out(i,j,k) = img(i,j,k); end
end
end
end
end
|
function RunBatNew( filename )
%RUNBAT runs a batch file via Windows start menu using Java Robot class
%Input:
% <filename> batch file (.bat)
%CL
% Get Windows version
winvers = system_dependent('getos');
% Create java robot to generate native system input events
import java.awt.Robot;
import java.awt.event.*;
robot = Robot();
% Open the windows start menu
% scrnsize = get(0,'screensize');
% robot.mouseMove(0,scrnsize(4));
% robot.mousePress(InputEvent.BUTTON1_MASK);
% robot.mouseRelease(InputEvent.BUTTON1_MASK);
% Open Win+R (Run) window instead
robot.keyPress(KeyEvent.VK_WINDOWS)
robot.keyPress(KeyEvent.VK_R)
robot.keyRelease(KeyEvent.VK_WINDOWS)
% Execute the batch file by typing the filename
if ~isempty(strfind(winvers,'10'))
% For Windows 10, batch execution via 'run'
pause(1)
lang = get(0,'Language');
if strcmp('de',lang(1:2))
typestr('Ausführen')
else
typestr('run')
end
robot.keyPress(KeyEvent.VK_ENTER)
pause(1)
% Type filename
typestr(filename)
robot.keyPress(KeyEvent.VK_ENTER)
else
% For Windows 7 and 8, batch execution via 'search'
typestr(filename)
robot.keyPress(KeyEvent.VK_ENTER)
end
end
function typestr( str )
%TYPESTRING types a given string on the keyboard using the java robot
% Create java robot to generate native system input events
import java.awt.Robot;
import java.awt.event.*;
robot = Robot();
pause(0.1)
for i = 1:length(str)
c = str(i);
if isstrprop(c,'punct') % Punctuation character
switch c
case '-'
robot.keyPress(KeyEvent.VK_MINUS)
case '.'
robot.keyPress(KeyEvent.VK_PERIOD)
case ':'
robot.keyPress(KeyEvent.VK_SHIFT)
robot.keyPress(KeyEvent.VK_PERIOD)
robot.keyRelease(KeyEvent.VK_SHIFT)
case '\' % ASCII value
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_NUMPAD9);
robot.keyPress(KeyEvent.VK_NUMPAD2);
robot.keyRelease(KeyEvent.VK_ALT);
end
elseif isstrprop(c,'wspace') % Space
robot.keyPress(KeyEvent.VK_SPACE);
elseif isstrprop(c,'digit') % Number
eval(strcat('robot.keyPress(KeyEvent.VK_NUMPAD',c,')'));
elseif strcmp(c,'ü')
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_NUMPAD1);
robot.keyPress(KeyEvent.VK_NUMPAD5);
robot.keyPress(KeyEvent.VK_NUMPAD4);
robot.keyRelease(KeyEvent.VK_ALT);
elseif strcmp(c,'ö')
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_NUMPAD1);
robot.keyPress(KeyEvent.VK_NUMPAD5);
robot.keyPress(KeyEvent.VK_NUMPAD3);
robot.keyRelease(KeyEvent.VK_ALT);
elseif strcmp(c,'ä')
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_NUMPAD1);
robot.keyPress(KeyEvent.VK_NUMPAD4);
robot.keyPress(KeyEvent.VK_NUMPAD2);
robot.keyRelease(KeyEvent.VK_ALT);
else
c = upper(c); % Upper case character
eval(strcat('robot.keyPress(KeyEvent.VK_',c,')'));
end
pause(0.01)
end
end
|
clear ; %clears all the variables
close all; %closes extra windows
clc %clears the screen
% =============================================================== Part 1: K MEANS ======================================================
% ----------------------------------------------------------(a)----------------------------------------------------------------
X = load('attr.txt');
y = load('label.txt');
[m n] = size(X);
K = 6; %no. of clusters
tic
idx = randperm(m, K); %generates unique K random integers between 1 to m inclusive.
final_cost = k_means(X, K, idx)
toc
% ----------------------------------------------------------(b)----------------------------------------------------------------
tic
J = zeros(10,1);
min_cost_idx = zeros(1,K);
min_cost = inf;
for i = 1 : 10
i
idx = randperm(m, K);
J(i) = k_means(X, K, idx)
if(J(i) < min_cost)
min_cost = J(i);
min_cost_idx = idx;
end
end
J
min_cost
toc
mu = X(min_cost_idx,:); %taking K random examples as the initial mu
J = zeros(60,1);
tic
for i = 1 : 60
c = best_cluster(X, K, mu); %Expectation Step
mu = update_means(X, K, c); %Minimization Step
J(i) = computeErrorMetric(X, c, mu); %finding the cost
end
toc
x = [1:60];
figure;
plot(x, J, '-', 'LineWidth', 0.7)
ylabel('Error'); % Set the y axis label
xlabel('No. of iterations'); % Set the x axis label
% ----------------------------------------------------------(c)----------------------------------------------------------------
mu = X(min_cost_idx,:);
accuracy_vector = zeros(60,1);
c_tmp = zeros(m, 1);
for iter = 1 : 60
c = best_cluster(X, K, mu); %Expectation Step
mu = update_means(X, K, c); %Minimization Step
for i = 1 : K
idx = find(c == i);
c_tmp(idx) = mode(y(idx));
end
accuracy_vector(iter) = length(find(c_tmp == y)) * 100 / m ;
end
figure;
plot(x, accuracy_vector, '-', 'LineWidth', 0.7)
ylabel('Accuracy'); % Set the y axis label
xlabel('No. of iterations'); % Set the x axis label
|
function [ X, interactionX ] = createAgeGenderSizeRegressionMatrix(groupVector,polynomialDims,varargin)
numCovars=length(varargin);
% Create a balanced groupVector
positiveGroup=find(groupVector > 0);
numPositive=length(positiveGroup);
negativeGroup=find(groupVector < 0);
numNegative=length(negativeGroup);
groupVector(positiveGroup)=sum(groupVector(positiveGroup))/numPositive*(numPositive/numNegative);
groupVector(negativeGroup)=sum(groupVector(negativeGroup))/numNegative*(numNegative/numPositive);
% Create polynomial expansions of the base covariates
for c=1:numCovars
baseCovar=cell2mat(varargin(c));
subX(1,:)=baseCovar-mean(baseCovar);
if polynomialDims(c)>1
for p=2:polynomialDims(c)
polyX=subX(1,:).^p;
polyX=polyX-mean(polyX);
polyX=polyX/max(polyX);
[~,~,stats]=glmfit(subX',polyX');
subX(p,:)=stats.resid;
end
end
if c==1
X=subX;
else
X=[X;subX];
end
clear subX
end
% Create a matrix to test for interactions
interactionX=X*0;
% Multiply main effect covariates by the group vector to
% create the interaction terms
for i=1:size(X,1)
interactionX(i,:)=X(i,:).*groupVector';
end
% Render the interaction terms orthogonal to the main effect
for i=1:size(X,1)
interaction=interactionX(i,:);
mainEffect=X(i,:);
[~,~,stats]=glmfit(mainEffect,interaction);
interactionX(i,:)=stats.resid;
end
% detect any interaction terms that are all zeros and remove them
goodColumns=ones(size(X,1),1);
for i=1:size(X,1)
if (max(interactionX(i,:))-min(interactionX(i,:)))<0.01
goodColumns(i)=0;
end
end
interactionX=interactionX(find(goodColumns==1),:);
gribble=1;
end
|
function interactive_graph_gui
% data
showLabels = true; % flag to determine whether to show node labels
prevIdx = []; % keeps track of 1st node clicked in creating edges
selectIdx = []; % used to highlight node selected in listbox
pts = zeros(0,2); % x/y coordinates of vertices
adj = sparse([]); % sparse adjacency matrix (undirected)
edd=sparse([]);
MinXLim=0;
MaxXLim=100;
MinYLim=0;
MaxYLim=100;
% create GUI
h = initGUI();
function h = initGUI()
h.fig = figure('Name','Interactive Graph', 'Resize','off');
h.ax = axes('Parent',h.fig, 'ButtonDownFcn',@onMouseDown, ...
'XLim',[MinXLim MaxXLim], 'YLim',[MinYLim MaxYLim], 'XTick',[], 'YTick',[], 'Box','on', ...
'Units','pixels', 'Position',[160 20 380 380]);
h.list = uicontrol('Style','listbox', 'Parent',h.fig, 'String',{}, ...
'Min',1, 'Max',1, 'Value',1, ...
'Position',[20 80 130 320], 'Callback',@onSelect);
uicontrol('Style','pushbutton', 'Parent',h.fig, 'String','Clear', ...
'Position',[20 20 60 20], 'Callback',@onClear);
uicontrol('Style','pushbutton', 'Parent',h.fig, 'String','Export', ...
'Position',[90 20 60 20], 'Callback',@onExport);
uicontrol('Style','pushbutton', 'Parent',h.fig, 'String','Delete', ...
'Position',[50 50 60 20], 'Callback',@onDelete);
h.cmenu = uicontextmenu('Parent',h.fig);
h.menu = uimenu(h.cmenu, 'Label','Show labels', 'Checked','off', ...
'Callback',@onCMenu);
set(h.list, 'UIContextMenu',h.cmenu)
h.pts = line(NaN, NaN, 'Parent',h.ax, 'HitTest','off', ...
'Marker','o', 'MarkerSize',10, 'MarkerFaceColor','b', ...
'LineStyle','none');
h.selected = line(NaN, NaN, 'Parent',h.ax, 'HitTest','off', ...
'Marker','o', 'MarkerSize',10, 'MarkerFaceColor','y', ...
'LineStyle','none');
h.prev = line(NaN, NaN, 'Parent',h.ax, 'HitTest','off', ...
'Marker','o', 'MarkerSize',20, 'Color','r', ...
'LineStyle','none', 'LineWidth',2);
h.edges = line(NaN, NaN, 'Parent',h.ax, 'HitTest','off', ...
'LineWidth',2, 'Color','g');
h.txt1 = [];
h.txt2 = [];
end
function onMouseDown(~,~)
% get location of mouse click (in data coordinates)
p = get(h.ax, 'CurrentPoint');
% determine whether normal left click was used or otherwise
if strcmpi(get(h.fig,'SelectionType'), 'Normal')
% add a new node
pts(end+1,:) = p(1,1:2);
adj(end+1,end+1) = 0;
else
% add a new edge (requires at least 2 nodes)
if size(pts,1) < 2, return; end
% hit test (find node closest to click location: euclidean distnce)
[dst,idx] = min(sum(bsxfun(@minus, pts, p(1,1:2)).^2,2));
% if sqrt(dst) > 0.025, return; end
if isempty(prevIdx)
% starting node (requires a second click to finish)
prevIdx = idx;
else
% add the new edge
adj(prevIdx,idx) =sqrt(((pts(prevIdx,1)-pts(idx,1))^2)+((pts(prevIdx,2)-pts(idx,2))^2));
prevIdx = [];
end
end
% update GUI
selectIdx = [];
redraw()
end
function onDelete(~,~)
% check that list of nodes is not empty
if isempty(pts), return; end
% delete selected node
idx = get(h.list, 'Value');
pts(idx,:) = [];
adj(:,idx) = [];
adj(idx,:) = [];
% clear previous selections
if prevIdx == idx
prevIdx = [];
end
selectIdx = [];
% update GUI
set(h.list, 'Value',max(min(idx,size(pts,1)),1))
redraw()
end
function onClear(~,~)
% reset everything
prevIdx = [];
selectIdx = [];
pts = zeros(0,2);
adj = sparse([]);
% update GUI
set(h.list, 'Value',1)
redraw()
end
function onExport(~,~)
% export nodes and adjacency matrix to base workspace
assignin('base', 'adj',adj+adj') % make it symmetric
assignin('base', 'xy',pts)
end
function onSelect(~,~)
% update index of currently selected node
selectIdx = get(h.list, 'Value');
redraw()
end
function onCMenu(~,~)
% flip state
showLabels = ~showLabels;
redraw()
end
function redraw()
% edges
p = nan(3*nnz(adj),2);
[i,j] = find(adj);
p(1:3:end,:) = pts(i,:);
p(2:3:end,:) = pts(j,:);
set(h.edges, 'XData',p(:,1), 'YData',p(:,2))
% nodes
set(h.pts, 'XData',pts(:,1), 'YData',pts(:,2))
set(h.prev, 'XData',pts(prevIdx,1), 'YData',pts(prevIdx,2))
set(h.selected, 'XData',pts(selectIdx,1), 'YData',pts(selectIdx,2))
% list of nodes
set(h.list, 'String',num2str(pts,'(%.3f,%.3f)'))
% node labels
if ishghandle(h.txt1)
delete(h.txt1);
end
if ishghandle(h.txt2)
delete(h.txt2);
end
if showLabels
set(h.menu, 'Checked','on')
h.txt1 = text(pts(:,1)+0.01, pts(:,2)+0.01, ...
num2str((1:size(pts,1))'), ...
'HitTest','off', 'FontSize',8, ...
'VerticalAlign','bottom', 'HorizontalAlign','left');
else
set(h.menu, 'Checked','off')
end
if ~isempty(find(adj, 1))
[xi,yi,val]=find(adj);
h.txt2 = text((pts(xi,1)+pts(yi,1))/2, (pts(xi,2)+pts(yi,2))/2, ...
num2str( val), ...
'HitTest','off', 'FontSize',8, ...
'VerticalAlign','bottom', 'HorizontalAlign','left');
end
% force refresh
drawnow
end
end
|
clear; close all; clc;
%% Threshhold, Adaptive Equal
% I = imread('fingerprint.png');
% I = double(I);
% fingim = otsu(I);
% figure('Name','Adaptive Equalization, Fingerprint');
% subplot(1,3,1);imagesc(I); title('Original Image');
% subplot(1,3,2);imagesc(fingim); colormap gray; title('Otsu Threshold');
% adt = AdaptiveEqualize(I);
% otAdt = otsu(adt);
% subplot(1,3,3); imagesc(otAdt);colormap gray; title('Otsu after Adaptive Equalizatoin');
%
%% Gaussain and Bilateral
% part a,b,c,d
I = imread('lena.png');
I = double(I);
subplot(2,3,1);imagesc(I); colormap gray; title('Original Im');
G = GaussianFilter(I,1);
subplot(2,3,2);imagesc(G); colormap gray; title('GaussianFltr sigma = 3');
B = BilateralFilter(I,3,10);
subplot(2,3,3);imagesc(B); colormap gray; title('BilateralFltr sd = 3 sr = 10');
dG = abs(I-G);
subplot(2,3,5);imagesc(dG); colormap gray; title('Original-Gaussian');
dB = abs(I-B);
sumdb = sum(sum(dB));
subplot(2,3,6); imagesc(dB); colormap gray;title('Original-Bilateral');
%% Part e
I = imread('lena.png');
I = double(I);
figure();
subplot(1,3,1);imagesc(I); colormap gray; title('Original Im');
B = BilateralFilter(I,3,100);
subplot(1,3,2);imagesc(B); colormap gray; title('BilateralFltr sd = 3 sr = 100');
dB = abs(I-B);
sumdb = sum(sum(dB));
subplot(1,3,3); imagesc(dB); colormap gray;title('Original-Bilateral');
%% part f and g
% I = imread('lena.png');
% I = double(I);
% figure();
% subplot(1,3,1);imagesc(I); colormap gray; title('Original Im');
%
% B = BilateralFilter(I,1000,10);
% subplot(1,3,2);imagesc(B); colormap gray; title('BilateralFltr sd = 1000 sr = 10');
%
% B = BilateralFilter(I,3,1000);
% subplot(1,3,3);imagesc(B); colormap gray; title('BilateralFltr sd = 3 sr = 1000');
%% House.png
% f = imread('house.png');
% f = double(f);
% g = f+20*randn(size(f));
%
% G = GaussianFilter(f,1);
% mn = size(f,1)*size(f,2);
% MSEf = sum(sum(minus(f,G).^2))/mn;
% MSEg = sum(sum(minus(f,g).^2))/mn;
% mseNoise = sprintf('Noise; MSE = %f',MSEg);
% mseFilter = sprintf('GaussianFlter sgm =3; MSE = %f',MSEf);
%
% subplot(1,3,1);imagesc(f); colormap gray; title('Original');
% subplot(1,3,2);imagesc(g); colormap gray; title(mseNoise);
% subplot(1,3,3);imagesc(G); colormap gray; title(mseFilter);
%
% figure();
% mse = [0,0,0,0,0,0];
% x = [5,10,20,40,60,100];
% B1 = BilateralFilter(g,3,5);
% mse(1) = 1./mn.*sum(sum(minus(f,B1).^2));
% mseFilter1 = sprintf('sgm =5; MSE = %f',mse(1));
% subplot(3,2,1);imagesc(B1); colormap gray;title(mseFilter1);
%
% B2 = BilateralFilter(g,3,10);
% mse(2) = 1./mn.*sum(sum(minus(f,B2).^2));
% mseFilter2 = sprintf('sgm =10; MSE = %f',mse(2));
% subplot(3,2,2);imagesc(B2); colormap gray;title(mseFilter2);
%
% B3 = BilateralFilter(g,3,20);
% mse(3) = 1./mn.*sum(sum(minus(f,B3).^2));
% mseFilter3 = sprintf('sgm =20; MSE = %f',mse(3));
% subplot(3,2,3);imagesc(B3); colormap gray;title(mseFilter3);
%
% B4 = BilateralFilter(g,3,40);
% mse(4) = 1./mn.*sum(sum(minus(f,B4).^2));
% mseFilter4 = sprintf('sgm =40; MSE = %f',mse(4));
% subplot(3,2,4);imagesc(B4); colormap gray;title(mseFilter4);
%
% B5 = BilateralFilter(g,3,60);
% mse(5) = 1./mn.*sum(sum(minus(f,B5).^2));
% mseFilter5 = sprintf('sgm =60; MSE = %f',mse(5));
% subplot(3,2,5);imagesc(B5); colormap gray;title(mseFilter5);
%
% B6 = BilateralFilter(g,3,100);
% mse(6) = 1./mn.*sum(sum(minus(f,B6).^2));
% mseFilter6 = sprintf('sgm =100; MSE = %f',mse(6));
% subplot(3,2,6);imagesc(B6); colormap gray;title(mseFilter6);
%
% figure();plot(x,mse);
|
%time_score driver
% sets paths to kml files and a wrfout, then runs the time_score function
kml_path = '/bigdisk/james.haley/wrfcycling/wrf-fire/wrfv2_fire/test/TIFs/doc.kml';
wrfout_path = '/bigdisk/james.haley/wrfcycling/wrf-fire/wrfv2_fire/test/cycling_best_ig_single/wrfout_d01_2013-08-13_00:00:00';
time_score(kml_path,wrfout_path)
|
function d = mismatch( h1, h2 )
% MISMATCH computes the mismatch distance between the two histograms
d = sum ( h1 ~= h2 );
end
|
clear
clc
close all
A = tf([1.3],[1,1.3])
G = tf([1],[.00303,0,0])
H = tf([1000],[1,1000])
GOL = A*G*H;
bode(GOL)
margin(GOL)
figure()
rlocus(GOL)
C1 = tf([1,1],[1,650])
C2 = tf([1,5],[1,300])
C = C1*C2;
CGOL = C*GOL
bode(CGOL)
margin(CGOL)
figure()
rlocus(CGOL)
K = 5;
GCL = K*CGOL/(1+K*CGOL);
figure()
step(GCL)
figure()
pzmap(GCL)
|
function mtlscale(infile, outfile, factor)
%function mtlscale(infile, outfile, factor)
[file_type,info_blocks,n_channels,n_lines, sampling_rate,...
first_line,last_line,n_directions,comment1, comment2] = mtlrh(infile)
if (file_type ~= 2) error('Wrong filetype'); return; end;
if (nargin < 3) factor=1; end;
index=0;
%if direction_matrix
if ((info_blocks-2) > 0)
direction_matrix=mtlrdir(infile,n_directions);
if (index ~= 0) direction_matrix(:) = direction_matrix(:,index); end;
% if time_delay exists read time_delay
if (( (info_blocks-2)*256 - n_directions*8) == (n_channels*4))
[delay_l,delay_r]=mtlrdel(infile,n_directions,binaural);
if (index ~= 0)
delay_l = delay_l(index);
if (binaural == 1) delay_r = delay_r(index); end;
end;
end;
end;
% write output_header
mtlwh(outfile,file_type,info_blocks,n_channels,n_lines, sampling_rate,...
first_line,last_line,n_directions,...
comment1, comment2);
% write directions;
% write delays;
if ((n_channels/n_directions) == 2) binaural=1; end;
n_dir=n_directions;
if (n_dir > 0)
n_byte=n_dir*2*4;
sn_del=length(delay_l);
if (sn_del > 0) n_byte=n_byte+n_dir*4*(binaural+1); end;
n_blocks=ceil(n_byte/256);
end;
info_blocks=2+n_blocks;
comment1 = [comment1 '; after scaling'];
mtlwh(outfile,file_type,info_blocks,n_channels,n_lines, sampling_rate,...
first_line,last_line,n_directions,...
comment1, comment2);
[fid,message] = fopen(outfile,'a','ieee-le');
if fid==-1 % file can't be opened
disp(message);
return;
end;
if ((n_blocks) > 0)
fseek(fid,512,'bof');
fwrite(fid,zeros(n_blocks*256,1),'float32');
fclose(fid);
end
%if direction_matrix
if ((n_blocks) > 0)
status=mtlwdir(outfile,direction_matrix)
if(length(delay_l) > 0) mtlwdel(outfile, delay_l,delay_r); end;
end
for n=1:n_channels
clc
disp(['MTLSCALE: channel ', num2str(n), ' of ', num2str(n_channels)] );
channel=mtlrch(infile,n);
status = mtlwch(outfile,channel*factor,n)
end;
fclose(fid);
|
function result = xcat(dim,varargin)
% Array concatenation with singleton expansion.
% Author: Vladimir Golkov
if ~isscalar(dim) && ~isempty(dim)
% dim not provided, first argument is array
varargin(2:end+1) = varargin; % TODO is this fast?
varargin{1} = dim;
end
sizelist = [];
for i=1:numel(varargin)
siz = size(varargin{i});
sizelist(:,end+1 : numel(siz)) = 1; % in case ndims(varargin{i}) is larger than largest previous ndims
sizelist(i,1:numel(siz)) = siz;
sizelist(i,numel(siz)+1 : end) = 1; % in case ndims(varargin{i}) is smaller than largest previous ndims
end
if isempty(dim)
dim = size(sizelist,2)+1; % determine dim automatically: choose next higher dimension
end
sizelist(:,end+1 : dim) = 1; % in case every ndims(varargin{i}) is smaller than concatenation dimension
resultsize = max(sizelist,[],1);
resultsize(dim) = sum(sizelist(:,dim));
e_dim = false(1,size(resultsize,2));
e_dim(dim) = true; % disregard concatenation dimension when checking dimension consistency
if ~all(all(bsxfun(@eq,sizelist,resultsize) | sizelist==1) | e_dim)
error('xcat:InsonsistentDimensions','Inconsistent dimensions. For each dimension, array sizes must either match or be equal to one.');
end
for i=1:numel(varargin)
newsize = resultsize./sizelist(i,:);
newsize(dim) = 1; % don't repeat along concatenation dimension
varargin{i} = repmat(varargin{i},newsize);
% TODO alternative to save working memory: in each loop iteration, do repmat, cat, discard
end
% prevent "Error using cat: Dimension for sparse matrix concatenation must be <= 2."
if dim>2 && any(cellfun(@issparse,varargin))
warning('Converting sparse to full...')
varargin = full(varargin); % this uses @cell/full.m
end
result = cat(dim,varargin{:});
|
function [T] = makebins(Set,Y,bins)
% MAKEBINS divides a given data set into cell bins
% -Set is the Data set (usually consisting of alignment identity score
% values and their respective sequences
% -Y is the result of running MATLAB's discretize function on Set
% -bins is the number of bins that the data will be divided into
T=cell(bins,1);
for i=1:size(Y,1)
num=Y(i,1);
elt=Set(i,:);
T{num,1}=[T{num,1}; elt];
end
end
|
% testing the stereo door corner camera
addpath(genpath('../utils/pyr'));
addpath(genpath('../corner_cam'));
addpath(genpath('../stereo_cam'));
close all; clear;
npx = 80;
width = npx/10;
floornpx = 80;
nsamples = 80;
% door is centered at origin
door_corner1 = [-1 0 0];
door_corner2 = [1 0 0];
door_width = abs(door_corner2(1) - door_corner1(1));
% we look at the shadow at the two corners of the door
xlocs1 = linspace(door_corner1(1), door_corner1(1)-1, floornpx);
xlocs2 = linspace(door_corner2(1), door_corner2(1)+1, floornpx);
ylocs = linspace(0, 1, floornpx);
% images behind the door
imdepths = [-5, -7];
imstarts = [2*width, 7*width];
nims = length(imstarts);
imgs = zeros([npx, npx, nims]);
scenex = linspace(door_corner1(1), door_corner2(1), npx);
sceneys = zeros([nims, npx]);
scenez = linspace(0, door_corner2(1), npx);
gt_depths = zeros(size(scenex));
obs1 = zeros([floornpx*floornpx, 1]);
obs2 = zeros(size(obs1));
figure;
for i = 1:nims
start = imstarts(i);
imgs(:,start:start+width,i) = 1;
sceneys(i,:) = ones(size(scenex)) * imdepths(i);
subplot(nims,1,i); imagesc(imgs(:,:,i));
axis off; title(sprintf('%d units depth', -imdepths(i)));
gt_depths = gt_depths + abs(imgs(1,:,i) .* sceneys(i,:));
% get observations
amat1 = cornerAmat(xlocs1, ylocs, scenex, sceneys(i,:));
obs1 = obs1 + amat1 * reshape(imgs(:,:,i), [npx*npx,1]);
amat2 = cornerAmat(xlocs2, ylocs, scenex, sceneys(i,:));
obs2 = obs2 + amat2 * reshape(imgs(:,:,i), [npx*npx,1]);
end
sigma = 0.5; beta = 100;
obs1_noisy = obs1 + sigma * randn(size(obs1));
obs2_noisy = obs2 + sigma * randn(size(obs1));
% plotting the shadow observations
figure;
subplot(211);
imagesc(xlocs1, ylocs, reshape(obs1_noisy, [floornpx, floornpx]));
subplot(212);
imagesc(xlocs2, ylocs, reshape(obs2_noisy, [floornpx, floornpx]));
% reconstructing a 1d picture from each door corner
thetas1 = [pi, pi/2];
tdir1 = sign(thetas1(2) - thetas1(1));
[amat1_1d, ~, ~] = allPixelAmat(door_corner1, floornpx, nsamples, thetas1);
angles1 = linspace(thetas1(1), thetas1(2), nsamples) + tdir1*pi;
thetas2 = [0, pi/2];
tdir2 = sign(thetas2(2) - thetas2(1));
[amat2_1d, ~, ~] = allPixelAmat(door_corner2, floornpx, nsamples, thetas2);
angles2 = linspace(thetas2(1), thetas2(2), nsamples) + tdir2*pi;
% spatial prior
bmat = eye(nsamples) - diag(ones([nsamples-1,1]), 1);
x1_1d = (amat1_1d'*amat1_1d/sigma^2 + bmat'*bmat*beta)\(amat1_1d'*obs1_noisy/sigma^2);
x2_1d = (amat2_1d'*amat2_1d/sigma^2 + bmat'*bmat*beta)\(amat2_1d'*obs2_noisy/sigma^2);
% x1_1d(x1_1d<0) = 0;
% x1_1d(x1_1d>1) = 1;
% x2_1d(x2_1d<0) = 0;
% x2_1d(x2_1d>1) = 1;
x1_1d = (x1_1d - min(x1_1d))/(max(x1_1d) - min(x1_1d));
x2_1d = (x2_1d - min(x2_1d))/(max(x2_1d) - min(x2_1d));
figure;
subplot(211); imagesc(angles1, 1:npx/2, repmat(x1_1d', [npx/2, 1]));
subplot(212); imagesc(angles2, 1:npx/2, repmat(x2_1d', [npx/2, 1]));
% estimate depth
% need to flip one of them; reverse orientations
x1_1d = x1_1d(end:-1:1);
angles1 = angles1(end:-1:1);
% for every window in x1_1d, we find the best matching window in x2_1d
winsize = 2;
energy = zeros(nsamples-winsize);
for i = 1:nsamples-winsize
win1 = x1_1d(i:i+winsize);
for j = 1:nsamples-winsize
win2 = x2_1d(j:j+winsize);
% energy(i,j) = -sum((win2-mean(win2)).*(win1-mean(win1)))/(std(win1)*std(win2));
energy(i,j) = sum((win2-win1).^2);
end
end
figure; imagesc(energy); title('energy between two reconstructions');
% the corresponding angles from the door corners, for each point
% only positive angles for this calculation
door_angle1 = abs(angles1(1:nsamples-winsize));
depths = zeros(size(door_angle1));
for i = 1:length(depths)
row = energy(i,:);
[val, idx] = min(row);
secondbest = row(row > val);
val2 = min(secondbest);
if val/val2 > 0.6
% too close together, assume we're not resolving to an actual object
depths(i) = 1e-2;
else
% take the angle of corner 2 of the best match
a2 = angles2(idx) - tdir2*pi;
a1 = door_angle1(i);
depths(i) = cot(a1) + cot(a2);
end
end
depths = abs(door_corner1(1) - door_corner2(1)) ./ depths;
locs1 = cot(door_angle1) .* depths - 1;
angle_ends = abs(angles1(1+winsize:nsamples));
locs2 = cot(angle_ends) .* depths - 1;
% [minval, minidx] = min(energy, [], 2);
% door_angle2 = angles2(minidx) - tdir2*pi;
% for each point, compute depth
% depths = abs(door_corner1(1) - door_corner2(1))./(cot(door_angle1) + cot(door_angle2));
figure; subplot(211);
plot(locs1(depths < 200), depths(depths < 200), 'ro');
hold on;
plot(locs2(depths < 200), depths(depths < 200), 'bo');
xlim([-1, 1]);
title('preliminary depth estimation of each point');
subplot(212); plot(scenex(gt_depths > 0), gt_depths(gt_depths > 0), 'bo');
xlim([-1, 1]); title('ground truth depths');
|
function LoadGamma(CLUT)
physicalDisplay = 1;
Display.ScreenID = 0;
[OriginalGammaTable, dacbits, reallutsize] = Screen('ReadNormalizedGammaTable', Display.ScreenID);%, physicalDisplay);
save('OriginalSetup3CLUT.mat', 'OriginalGammaTable');
CLUT = 'NIH_Setup3_ASUS_V27.mat';
load(CLUT);
AllScreens = Screen('Screens');
Stereomode = 4;
Text.Size = 60;
Eye = {'Left buffer (0)','Right buffer (1)'};
%================== IDENTIFY LEFT/RIGHT SCREENS AND BUFFERS ===============
[win Rect] = Screen('OpenWindow',0, 128, [],[],[],Stereomode);
for s = 1:2
Screen('SelectStereoDrawBuffer', win, s-1); % 0 = left eye buffer; 1 = right eye buffer
Screen('TextSize', win, Text.Size);
DrawFormattedText(win, Eye{s}, 'center', 'center', [0 0 0], []);
Screen('LoadNormalizedGammaTable', AllScreens, inverseCLUT{s});
end
Screen('Flip',win);
KbWait;
sca;
%================================== LOAD CLUTS ============================
% for i=1:numel(Lum)
% fprintf('CLUT %d for %s\n', i, Lum(i).DisplayName);
% end
% for Display = 1:2
% Screen('SelectStereoDrawBuffer', AllScreens, Display-1);
% Screen('LoadNormalizedGammaTable', AllScreens, inverseCLUT{Display}); % Load the original gamma table
% end
|
% min_angle = minAngle(angles_array, indices_of_min_energy)
% This function extracts the angles corresponding to minima in energy;
function min_angle = minAngle(energies, indices)
min_angle = angles_array(indices_of_min_energy);
end
|
close all
clear all
clc
%%
code_folder = '/Users/akira/Documents/GitHub/MN-Model/Test Size';
data_folder = '/Users/akira/Documents/GitHub/MN-Model/MN Parameter';
%%
type = 'S';
%%
model_folder = '/Users/akira/Documents/GitHub/Twitch-Based-Muscle-Model/Model Parameters/Model_8';
cd(model_folder)
load('modelParameter')
cd(code_folder)
[val,loc] = min(modelParameter.U_th);
testMN = loc;
MDR_d = modelParameter.MDR(testMN);
PDR_d = modelParameter.PDR(testMN);
I_max = 100;
I_th = 100*val;
slope_target = (PDR_d-MDR_d)/(I_max-I_th);
%%
% find a template MN whose minimal discharge rate is closest to the target
% minimal discharge rate
cd(data_folder)
load([type '_MDR'])
cd(code_folder)
[~,loc_min] = min(abs(MDR_d-MDR));
nMN = num2str(loc_min);
cd(data_folder)
load([type '_' nMN])
cd(code_folder)
%%
count = 1;
perturbation_amp = 0.3;
%%
% Fit the sloe of the f-I relationship by adjusting parameter g_Ks
for j = 1:5
j
amp_vec = 0:1:100;
mean_FR = zeros(1,length(amp_vec));
CoV_FR = zeros(1,length(amp_vec));
for i = 1:length(amp_vec)
Fs = 10000;
time = 0:1/Fs:5;
noise_amp = 0;
amp = amp_vec(i);
input = zeros(1,length(time));
input(1*Fs+1:end) = amp;
inputOpt = 1;
pltOpt = 0;
%%
[binary,V_s,V_d] = Cisi2008_function(param,time,input,Fs,noise_amp,inputOpt,pltOpt);
spike_time = find(binary(end-2*Fs+1:end));
ISI = diff(spike_time)/(Fs/1000);
mean_FR(i) = mean(1./ISI*1000);
CoV_FR(i) = std(1./ISI*1000)/mean_FR(i)*100;
end
%%
index_t = find(~isnan(mean_FR));
amp_th = amp_vec(index_t(1));
min_DR = mean_FR(index_t(1));
p_fit = polyfit(amp_vec(index_t),mean_FR(index_t),1);
y1 = polyval(p_fit,amp_vec(index_t));
error = slope_target - p_fit(1);
if error > 0
param.g_Ks = param.g_Ks - (param.g_Ks*perturbation_amp)./2.^(count-2);
else
param.g_Ks = param.g_Ks + (param.g_Ks*perturbation_amp)./2.^(count-2);
end
count = count + 1;
end
%%
% Fit the recruitment threshold by adjusting parameter I_r
mean_FR = zeros(1,length(amp_vec));
CoV_FR = zeros(1,length(amp_vec));
perturbation_amp = 0.3;
count = 1;
for j = 1:5
j
amp_vec = 0:0.1:50;
mean_FR = zeros(1,length(amp_vec));
CoV_FR = zeros(1,length(amp_vec));
error = I_th - amp_th;
if error > 0
param.I_r = param.I_r + (param.I_r*perturbation_amp)./2.^(count-2);
else
param.I_r = param.I_r - (param.I_r*perturbation_amp)./2.^(count-2);
end
for i = 1:length(amp_vec)
Fs = 10000;
time = 0:1/Fs:5;
noise_amp = 0;
amp = amp_vec(i);
input = zeros(1,length(time));
input(1*Fs+1:end) = amp;
inputOpt = 1;
pltOpt = 0;
[binary,V_s,V_d] = Cisi2008_function(param,time,input,Fs,noise_amp,inputOpt,pltOpt);
spike_time = find(binary(end-2*Fs+1:end));
ISI = diff(spike_time)/(Fs/1000);
mean_FR(i) = mean(1./ISI*1000);
CoV_FR(i) = std(1./ISI*1000)/mean_FR(i)*100;
end
index_t = find(~isnan(mean_FR));
amp_th = amp_vec(index_t(1));
min_DR = mean_FR(index_t(1));
p_fit = polyfit(amp_vec(index_t),mean_FR(index_t),1);
y1 = polyval(p_fit,amp_vec(index_t));
count = count + 1;
end
%% Plot the result
amp_vec = 0:0.1:100;
mean_FR = zeros(1,length(amp_vec));
CoV_FR = zeros(1,length(amp_vec));
for i = 1:length(amp_vec)
Fs = 10000;
time = 0:1/Fs:5;
noise_amp = 0;
amp = amp_vec(i);
input = zeros(1,length(time));
input(1*Fs+1:end) = amp;
inputOpt = 1;
pltOpt = 0;
[binary,V_s,V_d] = Cisi2008_function(param,time,input,Fs,noise_amp,inputOpt,pltOpt);
spike_time = find(binary(end-2*Fs+1:end));
ISI = diff(spike_time)/(Fs/1000);
mean_FR(i) = mean(1./ISI*1000);
CoV_FR(i) = std(1./ISI*1000)/mean_FR(i)*100;
end
index_t = find(~isnan(mean_FR));
amp_th = amp_vec(index_t(1));
min_DR = mean_FR(index_t(1));
p_fit = polyfit(amp_vec(index_t),mean_FR(index_t),1);
y1 = polyval(p_fit,amp_vec(index_t));
figure(1)
plot(amp_vec,mean_FR,'LineWidth',2)
hold on
plot(amp_vec(index_t),y1,'--k','LineWidth',1)
plot([min(amp_vec) max(amp_vec)],[MDR_d MDR_d],'--k','LineWidth',1)
plot([min(amp_vec) max(amp_vec)],[PDR_d PDR_d],'--k','LineWidth',1)
xlabel('Injected Current (nA)','FontSize',14)
ylabel('Dischage Rate (Hz)','FontSize',14)
set(gca,'TickDir','out');
set(gca,'box','off')
|
function z = polynomial_probs(data,n,resolution,lim)
C = mean(data,1);
R = max( vecnorm(data-C,2,2) );
P = @(L) max( 1 - (norm(L-C)/(3*R))^n, 0 );
X = linspace(-lim,lim,resolution);
Y = X;
[Xg,Yg] = meshgrid(X,Y);
Z = zeros(size(Xg));
for i=1:resolution^2
xx = Xg(i);
yy = Yg(i);
Z(i) = P([xx yy]);
end
z = Z/sum(sum(Z));
end
|
% function m = Gaussian(n)
clear; clc; close all;
n = 10;
m = zeros(ceil(6*n),ceil(6*n));
sigma = 3*n;
% for i = 1:n
% for j = 1:n
% top = -(i^2+j^2)/(2*sigma^2)
% m(i,j) = 1/(2*pi*sigma^2) * exp(top);
% end
% end
io = floor(size(m,1)/2);
jo = floor(size(m,2)/2);
for i = 1:size(m,1)
for j = 1:size(m,2)
top = -((i-io)^2/(2*sigma^2)+(j-jo)^2/(2*sigma^2));
m(i,j) = 1/(2*pi*sigma^2) * exp(top);
end
end
surf(m);
|
function [ output_args ] = StressPlot( Maps )
%STRESSPLOT Summary of this function goes here
% Detailed explanation goes here
figure
% S11 = Maps.S12_F;
% S12 = Maps.S12_F;
% S13 = Maps.S13_F;
% S22 = Maps.S22_F;
% S23 = Maps.S23_F;
% S33 = Maps.S33_F;
S11 = Maps.crop.S{1,1};
S12 = Maps.crop.S{1,2};
S13 = Maps.crop.S{1,3};
S22 = Maps.crop.S{2,2};
S23 = Maps.crop.S{2,3};
S33 = Maps.crop.S{3,3};
W = Maps.crop.W;
GNDs = Maps.crop.GNDs;
% Remove extreme values from plot
factor = 10;
S11(abs(S11)>factor*nanmean(abs(S11(:)))) = NaN;
S12(abs(S12)>factor*nanmean(abs(S12(:)))) = NaN;
S13(abs(S13)>factor*nanmean(abs(S13(:)))) = NaN;
S22(abs(S22)>factor*nanmean(abs(S22(:)))) = NaN;
S23(abs(S23)>factor*nanmean(abs(S23(:)))) = NaN;
S33(abs(S33)>factor*nanmean(abs(S33(:)))) = NaN;
minA = min([min(min(S11)) min(min(S12)) min(min(S13)) min(min(S22)) min(min(S23)) min(min(S33))]);
maxA = max([max(max(S11)) max(max(S12)) max(max(S13)) max(max(S22)) max(max(S23)) max(max(S33))]);
clim = [minA maxA];
Xvec = Maps.crop.X;
Yvec = Maps.crop.Y;
colormap jet
h1 = subplot(3,3,1);
pcolor(Xvec,Yvec,S11);shading interp;
set(gca,'Ydir','normal');
axis equal
xlim([min(Xvec) max(Xvec)])
ylim([min(Yvec) max(Yvec)])
colorbar
title('\fontsize{16}\sigma\fontsize{10}11')
h2 = subplot(3,3,2);
pcolor(Xvec,Yvec,S12);shading interp;
set(gca,'Ydir','normal');
axis equal
xlim([min(Xvec) max(Xvec)])
ylim([min(Yvec) max(Yvec)])
colorbar
title('\fontsize{16}\sigma\fontsize{10}12')
h3 = subplot(3,3,3);
pcolor(Xvec,Yvec,S13);shading interp;
set(gca,'Ydir','normal');
axis equal
xlim([min(Xvec) max(Xvec)])
ylim([min(Yvec) max(Yvec)])
colorbar
title('\fontsize{16}\sigma\fontsize{10}13')
h4 = subplot(3,3,5);
pcolor(Xvec,Yvec,S22);shading interp;
set(gca,'Ydir','normal');
axis equal
xlim([min(Xvec) max(Xvec)])
ylim([min(Yvec) max(Yvec)])
colorbar
title('\fontsize{16}\sigma\fontsize{10}22')
h5 = subplot(3,3,6);
pcolor(Xvec,Yvec,S23);shading interp;
set(gca,'Ydir','normal');
axis equal
xlim([min(Xvec) max(Xvec)])
ylim([min(Yvec) max(Yvec)])
colorbar
title('\fontsize{16}\sigma\fontsize{10}23')
h6 = subplot(3,3,9);
pcolor(Xvec,Yvec,S33);shading interp;
set(gca,'Ydir','normal');
axis equal
xlim([min(Xvec) max(Xvec)])
ylim([min(Yvec) max(Yvec)])
colorbar
title('\fontsize{16}\sigma\fontsize{10}33') %should be close to zero
h7 = subplot(3,3,4);
pcolor(Xvec,Yvec,W);shading interp;
set(gca,'Ydir','normal');
axis equal
xlim([min(Xvec) max(Xvec)])
ylim([min(Yvec) max(Yvec)])
colorbar
title('W')
h8 = subplot(3,3,7);
pcolor(Xvec,Yvec,GNDs); ;shading interp;
set(gca,'Ydir','normal');
axis equal
xlim([min(Xvec) max(Xvec)])
ylim([min(Yvec) max(Yvec)])
colormap(jet(256)); set(gcf,'position',[500,100,950,700]);
set(gca,'ColorScale','log'); set(gca,'CLim',[10^13 10^15.5]);
c = colorbar; c.Label.String = 'log';%labelling
title('GNDs')
set(gcf,'position',[800,80,1000,900])
% L = max([abs(minA) abs(maxA)]);
% set([h1 h2 h3 h4 h5 h6],'clim',[-L L]);
end
|
function T_new = transform_TFT(T_old,M1,M2,M3,inverse)
% Tranformed TFT
%
% short function to transform the TFT when an algebraic transformation
% has been aplied to the image points.
%
% if inverse==0 :
% from a TFT T_old assossiated to P1_old, P2_old, P3_old, find the new TFT
% T_new associated to P1_new=M1*P1_old, P2_new=M2*P2_old, P3_new=M3*P3_old.
% if inverse==1 :
% from a TFT T_old assossiated to P1_old, P2_old, P3 _old, find the new TFT
% T_new associated to M1*P1_new=P1_old, M2*P2_new=P2_old, M3*P3_new=P3_old.
%
% Copyright (c) 2017 Laura F. Julia <laura.fernandez-julia@enpc.fr>
% All rights reserved.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
if nargin<5
inverse=0;
end
if inverse==0
M1i=inv(M1); T_new=zeros(3,3,3);
T_new(:,:,1)=M2*(M1i(1,1)*T_old(:,:,1) + M1i(2,1)*T_old(:,:,2) + M1i(3,1)*T_old(:,:,3) )*M3.';
T_new(:,:,2)=M2*(M1i(1,2)*T_old(:,:,1) + M1i(2,2)*T_old(:,:,2) + M1i(3,2)*T_old(:,:,3) )*M3.';
T_new(:,:,3)=M2*(M1i(1,3)*T_old(:,:,1) + M1i(2,3)*T_old(:,:,2) + M1i(3,3)*T_old(:,:,3) )*M3.';
elseif inverse==1
M2i=inv(M2); M3i=inv(M3); T_new=zeros(3,3,3);
T_new(:,:,1)=M2i*(M1(1,1)*T_old(:,:,1) + M1(2,1)*T_old(:,:,2) + M1(3,1)*T_old(:,:,3) )*M3i.';
T_new(:,:,2)=M2i*(M1(1,2)*T_old(:,:,1) + M1(2,2)*T_old(:,:,2) + M1(3,2)*T_old(:,:,3) )*M3i.';
T_new(:,:,3)=M2i*(M1(1,3)*T_old(:,:,1) + M1(2,3)*T_old(:,:,2) + M1(3,3)*T_old(:,:,3) )*M3i.';
end
T_new=T_new/norm(T_new(:));
end
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 本函数用于下载指定证券代码(多个请用‘,’隔开)相应指定起始和截止日期之间的日
% 行情数据,保存到backtest Cache中,文件名为证券代码。
% 这里的日行情数据格式如下:
% 732686 4.460868254 4.48874868 4.419047614 4.453898147 11022101 6.39 215.9386515
% 732687 4.426017721 4.432987827 4.286615588 4.377226974 21426743 6.28 212.2213977
% 732688 4.377226974 4.426017721 4.321466121 4.342376441 9749282 6.23 210.5317369
% 732689 4.328436228 4.377226974 4.314496014 4.377226974 6720529 6.28 212.2213977
% 732690 4.356316654 4.426017721 4.307525908 4.328436228 7996673 6.21 209.8558726
% 日期 前复权开盘 前复权最高 前复权最低 前复权收盘 成交量 不复权收盘 后复权收盘
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function tool_download_callback(Path_backtest)
% 获取证券代码
prompt = {'证券代码(多个请用‘,’隔开):','StartDate','EndDate'};
dlg_title = '输入下载证券代码';
def ={'000300.SHI,000001.SHI','2012-01-01','2012-06-01'};
num_lines = 1;
options.Resize = 'on';
input_arg = inputdlg(prompt,dlg_title,num_lines,def,options);
if ~isempty(input_arg)
StartDate = input_arg{2};
EndDate = input_arg{3};
s = input_arg{1};
token = cell(1,1);
index = 1;
[token{index}, remain] = strtok(s,',');
% 下载指定证券代码日行情数据并保存到Cache中
writeintocache_backtest(token{index},StartDate,EndDate,Path_backtest);
while ~isempty(remain)
s = remain;
index = index + 1;
[token{index}, remain] = strtok(s,',');
writeintocache_backtest(token{index},StartDate,EndDate,Path_backtest);
end
end
end
|
%% Utility functions
classdef Util < handle
%%
methods (Static)
%%
% Scale and randomize data (matrix or filename). Use for
% convenience instead of individual functions.
function [data outfile] = scaleAndRandomize(data, numOutputs, inputMinValue, inputMaxValue, outputMinValue, outputMaxValue)
if nargin < 2
error('scaleAndRandomize(): Not enough input arguments.');
end
outfile = '';
if ischar(data)
outfile = Util.appendFilename(data, '_scaled_randomized');
data = xlsread(data);
end
switch nargin
case 2
data = Util.scale(data, numOutputs);
case 4
data = Util.scale(data, numOutputs, inputMinValue, inputMaxValue);
case 6
data = Util.scale(data, numOutputs, inputMinValue, inputMaxValue, outputMinValue, outputMaxValue);
otherwise
error('scaleAndRandomize(): Invalid number of arguments.');
end
data = Util.randomize(data);
if ~isempty(outfile)
xlswrite(outfile, data);
end
end
%%
% Scale `data` (a matrix or an xls filename) to the given min/max values.
% default input limits are [-1, 1] default output limits are [0, 1].
% If data is a filename, filename_scaled.xls will also be written.
function [scaled outfile] = scale(data, numOutputs, inputMinValue, inputMaxValue, outputMinValue, outputMaxValue)
if nargin < 2
error('scale(): Not enough input arguments.');
end
outfile = '';
if ischar(data)
outfile = Util.appendFilename(data, '_scaled');
data = xlsread(data);
end
if isempty(data)
error('scale(): Data is empty.');
end
if numOutputs < 1
error('scale(): There must be at least one output.');
end
numInputs = size(data, 2) - numOutputs;
if numInputs < 1
error('scale(): There must be at least one input.');
end
numSamples = size(data, 1);
if nargin == 3 || nargin == 5
error('scale(): maxValue must be defined if minValue is defined.');
end
if nargin == 4 || nargin == 6
if inputMinValue >= inputMaxValue || outputMinValue >= outputMaxValue
error('scale(): minValue must be less than maxValue.');
end
else
inputMinValue = -1;
inputMaxValue = 1;
outputMinValue = 0;
outputMaxValue = 1;
end
scaled = zeros(size(data));
scaleDiff = inputMaxValue - inputMinValue;
for i = 1 : numInputs
minval = min(data(:, i));
maxval = max(data(:, i));
dataDiff = maxval - minval;
for j = 1 : numSamples
scaled(j, i) = inputMinValue + ((data(j, i) - minval) * scaleDiff) / dataDiff;
end
end
scaleDiff = outputMaxValue - outputMinValue;
for i = (numInputs + 1) : (numInputs + numOutputs)
minval = min(data(:, i));
maxval = max(data(:, i));
dataDiff = maxval - minval;
for j = 1 : numSamples
scaled(j, i) = outputMinValue + ((data(j, i) - minval) * scaleDiff) / dataDiff;
end
end
if ~isempty(outfile)
xlswrite(outfile, scaled);
end
end
%%
% Randomize the rows in `data` (a matrix or an xls filename).
% If data is a filename, filename_randomized.xls will also be written.
function [randomized outfile] = randomize(data)
if nargin < 1
error('randomize(): Not enough input arguments.');
end
outfile = '';
if ischar(data)
outfile = Util.appendFilename(data, '_randomized');
data = xlsread(data);
end
if isempty(data)
error('randomize(): Data is empty.');
end
randomized = data(randperm(size(data,1)),:);
if ~isempty(outfile)
xlswrite(outfile, randomized);
end
end
%%
% Insert text between the end of a file's name and the extension.
function newname = appendFilename(filename, text)
if nargin < 2 || ~ischar(filename) || ~ischar(text)
error('appendFilename(): Two string arguments are required.');
end
strcat(filename, '');
[~, ~, ext] = fileparts(filename);
newname = strcat(filename(1:(length(filename) - length(ext))), text, ext);
end
end
methods (Access = private)
end
end
|
function [itrs, w_s, AUCs, timing] = OPAUC(X,y,X_test,y_test,eta,lambda,n_delta,u)
% Usage: OPAUC algorithm
% nargin < 8: standard OPAUC
% nargin == 8: OPAUCr (OPAUC for large scale data)
% Author: xzhang
% Date: 2017.11.16
% Version: 1.2
tic;
'new~'
% Returns
AUCs = [];
itrs = [];
timing = [];
w_s = [];
y = sparse(y);
% parameters
[d,n] = size(X);
if nargin < 8 || ~u
init = @zeros;
u = d;
std = 1;
else
disp('large scale and going with sparse setting ...')
std = 0;
init = @sparse;
R_hat_p = init(1,u);
R_hat_n = init(1,u);
end
T_p = 0;
T_n = 0;
c_p = init(d,1); c_n = init(d,1);
w = init(d,1);
Gamma_p = init(d,u);
Gamma_n = init(d,u);
delta = floor(n/n_delta);
sample = randsample(n, n, 'false');
for i = 1:n
xi = X(:,sample(i));
yi = y(sample(i));
if yi == 1
T_p = T_p+1;
c_p = c_p+(xi-c_p)/T_p;
if std
[Gamma_p,g] = std_update(xi,yi,w,lambda,Gamma_p,c_p,T_p,Gamma_n,c_n);
else
[Gamma_p,g,R_hat_p] = large_update(xi,yi,w,lambda,u,Gamma_p,R_hat_p,Gamma_n,c_n,R_hat_n,T_n);
end
else
T_n = T_n+1;
c_n = c_n+(xi-c_n)/T_n;
if std
[Gamma_n,g] = std_update(xi,yi,w,lambda,Gamma_n,c_n,T_n,Gamma_p,c_p);
else
[Gamma_n,g,R_hat_n] = large_update(xi,yi,w,lambda,u,Gamma_n,R_hat_n,Gamma_p,c_p,R_hat_p,T_p);
end
end
w = w-eta*g; % update model
% collect intermediate results
if mod(i,delta) == 0
[~,~,~,AUC] = perfcurve(y_test,w'*X_test,1);
disp(['***OPAUC: itr=', num2str(i), ', AUC=', num2str(AUC)]);
AUCs = cat(1, AUCs, AUC);
itrs = cat(1, itrs, i);
timing = cat(1, timing, toc);
w_s = cat(2, w_s, w);
end
end
end
function [Gamma,g] = std_update(xi,yi,w,lambda,Gamma,c,T,Gamma_op,c_op)
tmp = c;
Gamma = Gamma+(xi*xi'-Gamma)/T+tmp*tmp'-c*c';
g = lambda*w-yi*xi+yi*c_op+(xi-c_op)*(xi-c_op)'*w+Gamma_op*w;
end
function [Gamma,g,R_hat] = large_update(xi,yi,w,lambda,u,Gamma,R_hat,Gamma_op,c_op,R_hat_op,T_op)
% ri = randn(u,1);
ri = sparse(randn(u,1));
R_hat = R_hat + ri'/u; % update R_hat
Gamma = Gamma + xi*ri'/u; % update Z
tmp = xi-c_op;
g = lambda*w-yi*(tmp)+(tmp)*((tmp)'*w); %
if T_op > 0
% c_hat_op = (c_op*R_hat_op)/T_op;
g = g + Gamma_op*(Gamma_op'*w)/T_op-(c_op*(R_hat_op*R_hat_op')*(c_op'*w))/(T_op^2);
end
end
|
%Name:
% getu
%
%Purpose:
% This method will be used to apply the Dirichlet boundary condition.
% Where Vbound indicates we need the displacement to be zero.
%
%Parameters:
% A - ((2x#vertices) x (2x#vertices)) stiffness matrix
% F - ((2x#vertices) x 1) vector which represent the force value of each
% vertex
% Vbound (#vertices x 3) - matrix which shows which vertices were chosen
% to be Dirichlet boundary points
%
%Return Values:
% u - ((2x#vertices) x 1) vector which represents the displacment each
% vertex will recieve (our solution)
%
%Author:
% Shea Yonker
%
%Date:
% 09/18/2017
function [u] = getu(A,F,Vbound)
s = size(A,1);
u=zeros(s,1);
m=1;
B=zeros(s);
C=zeros(s,1);
for j=1:(s/2)
if (Vbound(j,3) == 1)
else
n=1;
for i=1:s
if (i<=(s/2))
if (Vbound(i,3) == 1)
else
B(m,n)=A(j,i);
n=n+1;
end
else
if (Vbound(i-(s/2),3) == 1)
else
B(m,n)=A(j,i);
n=n+1;
end
end
end
C(m)=F(j);
m=m+1;
end
end
for j=((s/2)+1):s
if (Vbound(j-(s/2),3) == 1)
else
n=1;
for i=1:s
if (i<=(s/2))
if (Vbound(i,3) == 1)
else
B(m,n)=A(j,i);
n=n+1;
end
else
if (Vbound(i-(s/2),3) == 1)
else
B(m,n)=A(j,i);
n=n+1;
end
end
end
C(m)=F(j);
m=m+1;
end
end
Areduced=zeros(m-1);
Freduced=zeros(m-1,1);
for j=1:m-1
for i=1:m-1
Areduced(j,i)=B(j,i);
end
Freduced(j)=C(j);
end
ureduced=Areduced\Freduced;
m=1;
for j=1:(s/2)
if (Vbound(j,3) == 1)
u(j)=0;
else
u(j)=ureduced(m);
m=m+1;
end
end
for j=((s/2)+1):s
if (Vbound(j-(s/2),3) == 1)
u(j)=0;
else
u(j)=ureduced(m);
m=m+1;
end
end
end
|
clc
clear
% x = [1,2,3;4,5,6;];
x = double(rgb2gray(imread('/Users/INNOCENTBOY/Documents/MATLAB/pic/256/4.1.01.tiff')));
h = ones(5,5);
% h = h/25;
M= size(x,1);
N= size(x,2);
m= size(h,1);
n= size(h,2);
h2 = fft2(h,M+m-1,N+n-1);
x2 = fft2(x,M+m-1,N+n-1);
h1 = fft2(h,M,N);
x1 = fft2(x,M,N);
out = x1.*h1;
out = ifft2(out);
out1 = x2.*h2;
out1 = ifft2(out1);
figure
subplot(2,2,1),imshow(mat2gray(x));
subplot(2,2,2),imshow(mat2gray(out));
subplot(2,2,3),imshow(mat2gray(out1));
|
function pixelgrid( h )
% Generates horizontal and vertical pixel grid lines for every pixel in an
% open image specified by the handle h. Operates on an already displayed
% figure and image.
%
% Required Input
% ==============
% h Figure handle correspoding to the open image to operate on
%
% Reference
% =========
% http://blogs.mathworks.com/steve/2011/02/17/pixel-grid/
%
h = findobj(h, 'type', 'image');
xdata = get(h, 'XData');
ydata = get(h, 'YData');
M = size(get(h, 'CData'), 1);
N = size(get(h, 'CData'), 2);
if M > 1
pixel_height = diff(ydata) / (M-1);
else
pixel_height = 1;
end
if N > 1
pixel_width = diff(xdata) / (M-1);
else
pixel_width = 1;
end
y_top = ydata(1) - (pixel_height / 2);
y_bottom = ydata(2) + (pixel_height / 2);
y = linspace(y_top, y_bottom, M+1);
x_left = xdata(1) - (pixel_width / 2);
x_right = xdata(2) + (pixel_width / 2);
x = linspace(x_left, x_right, N+1);
xv = zeros(1, 2*numel(x));
xv(1:2:end) = x;
xv(2:2:end) = x;
yv = repmat([y(1) ; y(end)], 1, numel(x));
yv(:,2:2:end) = flipud(yv(:,2:2:end));
xv = xv(:);
yv = yv(:);
yh = zeros(1, 2*numel(y));
yh(1:2:end) = y;
yh(2:2:end) = y;
xh = repmat([x(1) ; x(end)], 1, numel(y));
xh(:,2:2:end) = flipud(xh(:,2:2:end));
xh = xh(:);
yh = yh(:);
dark = [0.3 0.3 0.3];
light = [0.8 0.8 0.8];
hold on;
ax = ancestor(h, 'axes');
line('Parent', ax, 'XData', xh, 'YData', yh, 'Color', dark, ...
'LineStyle', '-', 'Clipping', 'off');
line('Parent', ax, 'XData', xh, 'YData', yh, 'Color', light, ...
'LineStyle', '--', 'Clipping', 'off');
line('Parent', ax, 'XData', xv, 'YData', yv, 'Color', dark, ...
'LineStyle', '-', 'Clipping', 'off');
line('Parent', ax, 'XData', xv, 'YData', yv, 'Color', light, ...
'LineStyle', '--', 'Clipping', 'off');
hold off;
end
|
function[nll] = negPopLogLikelihood(motion,f,r,params)
% function[nll] = negPopLogLikelihood(motion,f,r,params)
%
% motion: (e.g., specifies [direction, speed] for xz motion)
% f: tuning curve function handle
% r: "neural responses"
% params: parameters for tuning curves
%
% nll: negative loglikelihood
%
% see Graf, Kohn, Jazayeri, & Movshon (2011)
%
motion(2) = exp(motion(2));
ftemp = f(motion,params); % calculate tuning curve responses to particular motion
weights = log(ftemp);
ll = bsxfun(@times,weights,r) - ftemp - repmat(logfactorial(r),1,size(motion,1));
nll = -sum(ll);
|
function [mapout,xgrid] = sz1SM(data,paramstruct)
% SZ1SM, Significant derivative Zero crossings
% Steve Marron's matlab function
% Creates color map (function of location and bandwidth),
% showing statistical signicance of slope of smooth
% Colored (or gray level) as:
% blue (dark) at points where deriv sig > 0
% red (light) at points where deriv sig < 0
% purple (gray) at points where deriv roughly 0
% light gray where "effective sample size" < 5
%
% Inputs:
%
% data - Case 1: density estimation:
% either n x 1 column vector of 1-d data
% or vector of bincts, when imptyp = -1
% Case 2: regression:
% either n x 2 matrix of Xs (1st col) and Ys (2nd col)
% or g x 3 matrix of bincts, when imptyp = -1
% (3rd column is wt'd bin avg's of squares)
%
% paramstruct - a Matlab structure of input parameters
% Use: "help struct" and "help datatypes" to
% learn about these.
% Create one, using commands of the form:
%
% paramstruct = struct('field1',values1,...
% 'field2',values2,...
% 'field3',values3) ;
%
% where any of the following can be used,
% these are optional, misspecified values
% revert to defaults
%
% fields values
%
% vxgp vector of x grid parameters:
% 0 (or not specified) - use endpts of data and 401 bins
% [le; lr; nb] - le left, re right, and nb bins
%
% vhgp vector of h (bandwidth) grid parameters:
% 0 (or not specified) - use (2*binwidth) to (range),
% and 21 h's
% [hmin; hmax; nh] - use hmin to hmax and nh h's.
%
% imptyp flag indicating implementation type:
% -1 - binned version, and "data" is assumed to be
% bincounts of prebinned data
% CAUTION: for regression, also need
% to include bincounts of squares
% as a third column
% 0 (or not specified) - linear binned version
% and bin data here
%
% eptflag endpoint truncation flag (only has effect when imptyp = 0):
% 0 (or not specified) - move data outside range to
% nearest endpoint
% 1 - truncate data outside range
%
% ibdryadj index of boundary adjustment
% 0 (or not specified) - no adjustment
% 1 - mirror image adjustment
% 2 - circular design
% (only has effect for density estimation)
%
% iregtdist index for using Student's t distribution in regression
% 0 (or not specified) - use only Gaussian approximation
% 1 - use Student's t distribution quantiles in testing
% (only has effect for regression)
%
% alpha Usual "level of significance". I.e. C.I.s have coverage
% probability 1 - alpha. (0.05 when not specified)
%
% simflag Confidence Interval type (simultaneous vs. ptwise)
% 0 - Use Pointwise C.I.'s
% 1 (or not specified) - Use Row-wise Simultaneous C.I.'s
% 2 - Use Global Simultaneous C.I.'s
% 3 - Use Mixture 1 (Bonferroni across rows) Simultaneous C.I.'s
% 4 - Use Mixture 2 (Bonferroni across rows) Simultaneous C.I.'s
% 5 - 3 times Eff. SS global
% 6 - 3 times Eff. SS Row-wise
%
% icolor 1 (default) full color version of SiZer
% 0 fully black and white version
%
% titlestr string with title (only has effect when plot is made here)
% default is empty string, '', for no title
%
% titlefontsize font size for title
% (only has effect when plot is made here,
% and when the titlestr is nonempty)
% default is empty [], for Matlab default
%
% xlabelstr string with x axis label
% (only has effect when plot is made here)
% default is empty string, '', for no xlabel
%
% ylabelstr string with y axis label
% (only has effect when plot is made here)
% default is empty string, '', for no ylabel
%
% labelfontsize font size for axis labels
% (only has effect when plot is made here,
% and when a label str is nonempty)
% default is empty [], for Matlab default
%
% iplot 1 - plot even when there is numerical output
% 0 - (default) only plot when no numerical output
%
%
% Outputs:
% (none) - Draws a gray level map (in the current axes)
% mapout - output of indices into color map
% xgrid - col vector grid of points at which estimate(s) are
% evaluted (useful for plotting), unless grid is input,
% can also get this from linspace(le,re,nb)'
%
% Assumes path can find personal functions:
% vec2matSM.m
% lbinrSM.m
%
% Copyright (c) J. S. Marron 1997-2001
% First set all parameters to defaults
vxgp = 0 ;
vhgp = 0 ;
imptyp = 0 ;
eptflag = 0 ;
ibdryadj = 0 ;
iregtdist = 0 ;
alpha = 0.05 ;
simflag = 1 ;
icolor = 1 ;
titlestr = '' ;
titlefontsize = [] ;
xlabelstr = '' ;
ylabelstr = '' ;
labelfontsize = [] ;
iplot = 0 ;
% Now update parameters as specified,
% by parameter structure (if it is used)
%
if nargin > 1 ; % then paramstruct has been added
if isfield(paramstruct,'vxgp') ; % then change to input value
vxgp = getfield(paramstruct,'vxgp') ;
end ;
if isfield(paramstruct,'vhgp') ; % then change to input value
vhgp = getfield(paramstruct,'vhgp') ;
end ;
if isfield(paramstruct,'eptflag') ; % then change to input value
eptflag = getfield(paramstruct,'eptflag') ;
end ;
if isfield(paramstruct,'ibdryadj') ; % then change to input value
ibdryadj = getfield(paramstruct,'ibdryadj') ;
end ;
if isfield(paramstruct,'iregtdist') ; % then change to input value
iregtdist = getfield(paramstruct,'iregtdist') ;
end ;
if isfield(paramstruct,'alpha') ; % then change to input value
alpha = getfield(paramstruct,'alpha') ;
end ;
if isfield(paramstruct,'simflag') ; % then change to input value
simflag = getfield(paramstruct,'simflag') ;
end ;
if isfield(paramstruct,'icolor') ; % then change to input value
icolor = getfield(paramstruct,'icolor') ;
end ;
if isfield(paramstruct,'titlestr') ; % then change to input value
titlestr = getfield(paramstruct,'titlestr') ;
end ;
if isfield(paramstruct,'titlefontsize') ; % then change to input value
titlefontsize = getfield(paramstruct,'titlefontsize') ;
end ;
if isfield(paramstruct,'xlabelstr') ; % then change to input value
xlabelstr = getfield(paramstruct,'xlabelstr') ;
end ;
if isfield(paramstruct,'ylabelstr') ; % then change to input value
ylabelstr = getfield(paramstruct,'ylabelstr') ;
end ;
if isfield(paramstruct,'labelfontsize') ; % then change to input value
labelfontsize = getfield(paramstruct,'labelfontsize') ;
end ;
if isfield(paramstruct,'iplot') ; % then change to input value
iplot = getfield(paramstruct,'iplot') ;
end ;
if isfield(paramstruct,'imptyp') ; % then change to input value
imptyp = getfield(paramstruct,'imptyp') ;
end ;
end ; % of resetting of input parameters
% detect whether density or regression data
%
if size(data,2) == 1 ; % Then is density estimation
xdat = data(:,1) ;
idatyp = 1 ;
itdist = 0 ;
% use Gaussian distribution, not t
else ; % Then assume regression ;
xdat = data(:,1) ;
ydat = data(:,2) ;
idatyp = 2 ;
if iregtdist == 1 ;
itdist = 1 ;
% use t distribution
else ;
itdist = 0 ;
% use Gaussian distribution, not t
end ;
end ;
% Set x grid stuff
%
n = length(xdat) ;
if vxgp == 0 ; % then use standard default x grid
vxgp = [min(xdat),max(xdat),401] ;
end ;
left = vxgp(1) ;
right = vxgp(2) ;
ngrid = vxgp(3) ;
xgrid = linspace(left,right,ngrid)' ;
% col vector to evaluate smooths at
cxgrid = xgrid - mean(xgrid) ;
% centered version, gives numerical stability
% Set h grid stuff
%
if vhgp == 0 ; % then use standard default h grid
range = right - left ;
binw = range / (ngrid - 1) ;
vhgp = [2 * binw,range,21] ;
end ;
hmin = vhgp(1) ;
hmax = vhgp(2) ;
nh = vhgp(3) ;
if nh == 1 ;
vh = hmax ;
else ;
if hmin < hmax ; % go ahead with vh construction
vh = logspace(log10(hmin),log10(hmax),nh) ;
else ; % bad inputs, warn and quit
disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') ;
disp('!!! Error from sz1SM.m: !!!') ;
disp('!!! Bad inputs in vhgp, !!!') ;
disp('!!! Reguires vhgp(1) < vhgp(2) !!!') ;
disp('!!! Terminating execution !!!') ;
disp('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') ;
return ;
end ;
end ;
% Bin the data (if needed)
%
if idatyp == 1 ; % Treating as density estimation
if imptyp == -1 ; % Then data have already been binned
bincts = data ;
else ; % Then need to bin data
bincts = lbinrSM(xdat,vxgp,eptflag) ;
end ;
elseif idatyp == 2 ; % Treating as regression
if imptyp == -1 ; % Then data have already been binned
bincts = data(:, [1 2]) ;
bincts2 = data(:, [1 3]) ;
else ; % Then need to bin data
bincts = lbinrSM([xdat ydat],vxgp,eptflag) ;
bincts2 = lbinrSM([xdat, ydat.^2],vxgp,eptflag) ;
end ;
end ;
n = sum(bincts(:,1)) ;
% put this here in case of truncations during binning
% Construct Surfaces
%
mdsurf = [] ;
% Derivative surface
mesurf = [] ;
% Effective sample size surface
mvsurf = [] ;
% Estimated Variance of Derivative
if itdist == 0 ;
vgq = [] ;
% Vector of Gaussian Quantiles (for simultaneous CI's)
elseif itdist == 1 ;
mtq = [] ;
% matrix of t Quantiles (for simultaneous CI's)
end ;
% Create grid for kernel values
delta = (right - left) / (ngrid - 1) ; % binwidth
k = ngrid - 1 ; % index of last nonzero entry of kernel vector
% Loop through bandwidths
ihprevcalc = 0 ;
% indicator of whether have done the full calculation
% (not done when all locations have ESS < 5)
for ih = 1:nh ;
h = vh(ih) ;
% Set common values
arg = linspace(0,k * delta / h,k + 1)' ;
kvec = exp(-(arg.^2) / 2) ;
kvec = [flipud(kvec(2:k+1)); kvec] ;
% construct symmetric kernel
if idatyp == 1 ; % Doing density estimation
% main lines from gpkde.m, via nmsur5.m
% do boundary adjustment if needed
%
if ibdryadj == 1 ; % then do mirror image adjustment
babincts = [flipud(bincts); bincts; flipud(bincts)] ;
elseif ibdryadj == 2 ; % then do circular design adjustment
babincts = [bincts; bincts; bincts] ;
else ;
babincts = bincts ;
end ;
% Vector of Effective sample sizes
% (notation "s0" is consistent with below)
ve = conv(babincts,kvec) ;
if ibdryadj == 1 | ibdryadj == 2 ; % then did boundary adjustment
ve = ve(ngrid+k+1:k+2*ngrid) ;
else ;
ve = ve(k+1:k+ngrid) ;
end ;
% denominator of NW est.
% (same as sum for kde)
kvecd = -arg .* exp(-(arg.^2) / 2) / sqrt(2 * pi) ;
kvecd = [-flipud(kvecd(2:k+1)); kvecd] ;
% construct symmetric kernel
vd = conv(babincts,kvecd) ;
vv = conv(babincts,kvecd.^2) ;
if ibdryadj == 1 | ibdryadj == 2 ; % then did boundary adjustment
vd = vd(ngrid+k+1:k+2*ngrid) / (n * h^2) ;
vv = vv(ngrid+k+1:k+2*ngrid) / (n * h^4) ;
else ;
vd = vd(k+1:k+ngrid) / (n * h^2) ;
vv = vv(k+1:k+ngrid) / (n * h^4) ;
end ;
vv = vv - vd.^2 ;
vv = vv / n ;
% did this outsidea loop in nmsur5.m
else ; % Doing regression
% using modification of lines from gpnpr.m
% main lines from gpnpr.m, via szeg4.m
% Vector of Effective sample sizes
% (notation "s0" is consistent with below)
ve = conv(bincts(:,1),kvec) ;
ve = ve(k+1:k+ngrid) ;
% denominator of NW est.
% (same as sum for kde)
flag = (ve < 1) ;
% locations with effective sample size < 1
ve(flag) = ones(sum(flag),1) ;
% replace small sample sizes by 1 to avoid 0 divide
% no problem below, since gets grayed out
s1 = conv(bincts(:,1) .* cxgrid , kvec) ;
s1 = s1(k+1:k+ngrid) ;
s2 = conv(bincts(:,1) .* cxgrid.^2 , kvec) ;
s2 = s2(k+1:k+ngrid) ;
t0 = conv(bincts(:,2),kvec) ;
t0 = t0(k+1:k+ngrid) ;
% numerator of NW est.
xbar = conv(bincts(:,1) .* cxgrid , kvec) ;
xbar = xbar(k+1:k+ngrid) ;
% Weighted sum of X_i
xbar = xbar ./ ve ;
% Weighted avg of X_i
t1 = conv(bincts(:,2) .* cxgrid , kvec) ;
t1 = t1(k+1:k+ngrid) ;
numerd = t1 - t0 .* xbar ;
% sum(Y_i * (X_i - xbar)) * W (weighted cov(Y,X))
denomd = s2 - 2 * s1 .* xbar + ve .* xbar.^2 ;
% sum((X_i - xbar)^2) * W (weighted var(X))
flag2 = denomd < (10^(-10) * mean(denomd)) ;
% for local linear, need to also flag locations where this
% is small, because could have many observaitons piled up
% at one location
ve(flag2) = ones(sum(flag2),1) ;
% also reset these, because could have more than 5 piled up
% at a single point, but nothing else in window
flag = flag | flag2 ;
% logical "or", which flags both types of locations
% to avoid denominator problems
denomd(flag) = ones(sum(flag),1) ;
% this avoids zero divide problems, OK, since grayed out later
mhat = t0 ./ ve ;
vd = numerd ./ denomd ;
% linear term from local linear fit (which est's deriv).
% (sometimes called betahat)
sig2 = conv(bincts2(:,2),kvec) ;
sig2 = sig2(k+1:k+ngrid) ;
sig2 = sig2 ./ ve - mhat.^ 2 ;
flag2 = sig2 < (10^(-10) * mean(sig2)) ;
ve(flag2) = ones(sum(flag2),1) ;
% also reset these
flag = flag | flag2 ;
% logical "or", which flags both types of locations
% to avoid denominator problems
sig2(flag) = ones(sum(flag),1) ;
% this avoids zero divide problems, OK, since grayed out later
rho2 = vd.^2 .* (denomd ./ (sig2 .* ve)) ;
sig2res = (1 - rho2) .* sig2 ;
% get the residual variance from local linear reg.
u0 = conv(bincts(:,1) .* sig2res , kvec.^2) ;
u0 = u0(k+1:k+ngrid) ;
u1 = conv(bincts(:,1) .* sig2res .* cxgrid , kvec.^2) ;
u1 = u1(k+1:k+ngrid) ;
u2 = conv(bincts(:,1) .* sig2res .* cxgrid.^2 , kvec.^2) ;
u2 = u2(k+1:k+ngrid) ;
vv = u2 - 2 * u1 .* xbar + u0 .* xbar.^2 ;
vv = vv ./ denomd.^2 ;
% vector of variances of slope est. (from local linear)
end ;
% Get quantiles, for CI's
flag = (ve >= 5) ;
% locations where effective sample size >= 5
if sum(flag) > 0 ;
if simflag == 0 ; % do pt'wise CI's
if itdist == 0 ;
gquant = norminv(1 - (alpha / 2)) ;
elseif itdist == 1 ;
vtquant = tinv(1 - (alpha / 2),ve-1) ;
end ;
elseif simflag == 1 ; % do row-wise simultaneous CI's
nxbar = mean(ve(flag)) ;
% Crude average effective sample size
numind = n / nxbar ;
% Effective number of independent groups
beta = (1 - alpha)^(1/numind) ;
if itdist == 0 ;
gquant = -norminv((1 - beta) / 2) ;
elseif itdist == 1 ;
vtquant = -tinv((1 - beta) / 2,ve-1) ;
end ;
elseif simflag == 2 ; % do Global Simultaneous C.I.'s
if ihprevcalc == 0 ; % then are at finest scale,
% where have not done a calculation yet
ihprevcalc = 1 ;
% turn off this indicator, so won't calculate this again
nxbar = mean(ve(flag)) ;
% Crude average effective sample size
numind = n / nxbar ;
% Effective number of independent groups
numind = 2 * numind - 1 ;
% modify to make global
beta = (1 - alpha)^(1/numind) ;
end ; % at other scales, continue to use this value
if itdist == 0 ;
gquant = -norminv((1 - beta) / 2) ;
elseif itdist == 1 ;
vtquant = -tinv((1 - beta) / 2,ve-1) ;
end ;
elseif simflag == 3 ; % do Mixture 1 (Bonferroni across rows) Simul. C.I.'s
nxbar = mean(ve(flag)) ;
% Crude average effective sample size
numind = n / nxbar ;
% Effective number of independent groups
beta = (1 - (alpha / nh))^(1/numind) ;
% only change from simflag = 1 above is: alpha ---> alpha / nh
% (Bonferroni across rows, calculation)
if itdist == 0 ;
gquant = -norminv((1 - beta) / 2) ;
elseif itdist == 1 ;
vtquant = -tinv((1 - beta) / 2,ve-1) ;
end ;
elseif simflag == 4 ; % do Mixture 2 (Bonferroni across rows) Simul. C.I.'s
nxbar = mean(ve(flag)) ;
% Crude average effective sample size
numind = n / nxbar ;
% Effective number of independent groups
if itdist == 0 ;
gquant = numind ;
elseif itdist == 1 ;
vtquant = numind ;
end ;
% store the Effective number of groups, for later processing
% CAUTION: in this case, don't return quantiles, but just
% numind, for later turning into quantiles
elseif simflag == 5 ; % do 3 times Global Simultaneous C.I.'s
if ihprevcalc == 0 ; % then are at finest scale,
% where have not done a calculation yet
ihprevcalc = 1 ;
% turn off this indicator, so won't calculate this again
nxbar = mean(ve(flag)) ;
% Crude average effective sample size
numind = n / nxbar ;
% Effective number of independent groups
numind = 6 * numind - 5 ;
% modify to make global
beta = (1 - alpha)^(1/numind) ;
end ; % at other scales, continue to use this value
if itdist == 0 ;
gquant = -norminv((1 - beta) / 2) ;
elseif itdist == 1 ;
vtquant = -tinv((1 - beta) / 2,ve-1) ;
end ;
elseif simflag == 6 ; % do 3 times row-wise simultaneous CI's
nxbar = mean(ve(flag)) ;
% Crude average effective sample size
numind = n / nxbar ;
% Effective number of independent groups
numind = 3 * numind - 2 ;
beta = (1 - alpha)^(1/numind) ;
if itdist == 0 ;
gquant = -norminv((1 - beta) / 2) ;
elseif itdist == 1 ;
vtquant = -tinv((1 - beta) / 2,ve-1) ;
end ;
end ;
else ;
if itdist == 0 ;
gquant = inf ;
elseif itdist == 1 ;
vtquant = inf * ones(ngrid,1) ;
end ;
end ;
mdsurf = [mdsurf vd] ;
mesurf = [mesurf ve] ;
mvsurf = [mvsurf vv] ;
if itdist == 0 ;
vgq = [vgq gquant] ;
elseif itdist == 1 ;
mtq = [mtq vtquant] ;
end ;
end ;
% finish vgq calculation (if needed)
% (i.e. if only stored numind, instead of quantiles above)
%
if simflag == 4 ; % do Mixture 2 (Bonferroni across rows) Simul. C.I.'s
if itdist == 0 ;
vnumind = vgq ;
% unpack column vector of number of indep blocks, stored above
elseif itdist == 1 ;
vnumind = mtq ;
% unpack column vector of number of indep blocks, stored above
end ;
vrowfactor = vnumind .^ (0.5) ;
vrowfactor = vrowfactor / sum(vrowfactor) ;
vbeta = (1 - (alpha .* vrowfactor)).^ (1 ./ vnumind) ;
if itdist == 0 ;
vgq = -norminv((1 - vbeta) / 2) ;
elseif itdist == 1 ;
mtq = -tinv(vec2matSM((1 - vbeta) / 2,ngrid), vec2matSM(ve-1,nh)) ;
% note first is an nh x 1 column vector
% and second is a 1 x ngrid row vector
end ;
end ;
%vrowfactor
%1/nh
%vnumind
%vgq
%pauseSM
% Construct scale space CI surfaces
%
if itdist == 0 ;
if nh > 1 ; % then have full matrices
mloci = mdsurf - vec2matSM(vgq,ngrid) .* sqrt(mvsurf) ;
% Lower confidence (simul.) surface for derivative
mhici = mdsurf + vec2matSM(vgq,ngrid) .* sqrt(mvsurf) ;
% Upper confidence (simul.) surface for derivative
else ; % have only vectors (since only one h)
mloci = mdsurf - vgq * sqrt(mvsurf) ;
% Lower confidence (simul.) surface for derivative
mhici = mdsurf + vgq * sqrt(mvsurf) ;
% Upper confidence (simul.) surface for derivative
end ;
elseif itdist == 1 ;
mloci = mdsurf - mtq .* sqrt(mvsurf) ;
% Lower confidence (simul.) surface for derivative
mhici = mdsurf + mtq .* sqrt(mvsurf) ;
% Upper confidence (simul.) surface for derivative
end ;
% Construct "color map", really assignment
% of pixels to integers, with idea:
% 1 (very dark) - Deriv. Sig. > 0
% 2 (darker gray) - Eff. SS < 5
% 3 (lighter gray) - Eff. SS >= 5, but CI contains 0
% 4 (very light) - Deriv. Sig. < 0
mapout = 3 * ones(size(mloci)) ;
% default is purple (middle lighter gray)
flag = (mloci > 0) ;
% matrix of ones where lo ci above 0
ssflag = sum(sum(flag)) ;
if ssflag > 0 ;
mapout(flag) = ones(ssflag,1) ;
% put blue (dark grey) where significantly positive
end ;
flag = (mhici < 0) ;
% matrix of ones where hi ci below 0
ssflag = sum(sum(flag)) ;
if ssflag > 0 ;
mapout(flag) = 4 * ones(ssflag,1) ;
% put red (light gray) where significantly negative
end ;
flag = (mesurf <= 5) ;
% matrix of ones where effective np <= 5 ;
ssflag = sum(sum(flag)) ;
if ssflag > 0 ;
mapout(flag) = 2 * ones(ssflag,1) ;
% put middle darker gray where effective sample size < 5
end ;
% Transpose for graphics purposes
mapout = mapout' ;
% Make plots if no numerical output requested
%
if nargout == 0 | ...
iplot == 1 ; % Then make a plot
if icolor ~= 0 ; % Then go for nice colors in sizer and sicon
% Set up colorful color map
cocomap = [0, 0, 1; ...
.35, .35, .35; ...
.5, 0, .5; ...
1, 0, 0; ...
1, .5, 0; ...
.35, .35, .35; ...
0, 1, 0; ...
0, 1, 1] ;
colormap(cocomap) ;
else ; % Then use gray scale maps everywhere
% Set up gray level color map
comap = [.2, .2, .2; ...
.35, .35, .35; ...
.5, .5, .5; ...
.8, .8, .8] ;
colormap(comap) ;
end ;
image([left,right],[log10(hmin),log10(hmax)],mapout) ;
set(gca,'YDir','normal') ;
if ~isempty(titlestr) ;
if isempty(titlefontsize) ;
title(titlestr) ;
else ;
title(titlestr,'FontSize',titlefontsize) ;
end ;
end ;
if ~isempty(xlabelstr) ;
if isempty(labelfontsize) ;
xlabel(xlabelstr) ;
else ;
xlabel(xlabelstr,'FontSize',labelfontsize) ;
end ;
end ;
if ~isempty(ylabelstr) ;
if isempty(labelfontsize) ;
ylabel(ylabelstr) ;
else ;
ylabel(ylabelstr,'FontSize',labelfontsize) ;
end ;
end ;
end ;
|
classdef AbstractAnimator < handle
% An abstract animator class
%
% @author omar @date 2017-06-01
%
% Copyright (c) 2017, UMICH Biped Lab
% All right reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted only in compliance with the BSD 3-Clause
% license, see
% http://www.opensource.org/licenses/BSD-3-Clause
properties(Access = private)
tmr timer
end
properties (GetAccess = protected, SetAccess = immutable)
fig
axs
end
properties (Access = public)
currentTime double
speed double
updateWorldPosition logical
end
properties (Access = public)
isLooping logical
pov frost.Animator.AnimatorPointOfView
startTime double
endTime double
end
properties (GetAccess = public, SetAccess = immutable)
TimerDelta double
end
properties (Dependent, Access = public)
isPlaying logical
end
properties (Access = private)
x_all;
t_all;
text;
ground;
end
properties (Access = public)
display
end
methods
function obj = AbstractAnimator(display, t, x, varargin)
% if exist('f', 'var')
% obj.fig = f;
% obj.axs = axes(obj.fig);
% else
% obj.fig = figure();
% obj.axs = axes(obj.fig);
% end
obj.display = display;
obj.fig = display.fig;
obj.axs = display.axs;
obj.t_all = t;
obj.x_all = x;
obj.startTime = t(1);
obj.currentTime = obj.startTime;
obj.endTime = t(end);
% setup timer
obj.speed = 1;
obj.TimerDelta = round(1/30,3);
obj.pov = frost.Animator.AnimatorPointOfView.Free;
obj.tmr = timer;
obj.tmr.Period = obj.TimerDelta;
obj.tmr.ExecutionMode = 'fixedRate';
obj.tmr.TimerFcn = @(~, ~) obj.Animate();
% Define Terrain
if isempty(varargin)
[terrain.Tx, terrain.Ty] = meshgrid(-10:1:10, -10:1:10);
terrain.Tz = 0.*terrain.Tx;
else
terrain = varargin{1};
end
obj.ground = surf(terrain.Tx,terrain.Ty,terrain.Tz,'FaceColor',[0.5 0.8 0.5]); hold on;
end
function playing = get.isPlaying(obj)
playing = strcmp(obj.tmr.Running, 'on');
end
function set.isPlaying(obj, play)
if ~obj.isPlaying && play
start(obj.tmr);
notify(obj, 'playStateChanged');
elseif obj.isPlaying && ~play
stop(obj.tmr);
notify(obj, 'playStateChanged');
end
end
function set.currentTime(obj, time)
obj.currentTime = time;
if obj.currentTime > obj.endTime %#ok<*MCSUP>
obj.currentTime = obj.endTime;
elseif obj.currentTime < obj.startTime
obj.currentTime = obj.startTime;
end
end
end
methods (Sealed)
function Animate(obj, Freeze)
if ~exist('Freeze', 'var')
Freeze = false;
end
if obj.currentTime >= obj.endTime
obj.currentTime = obj.endTime;
x = GetData(obj, obj.currentTime);
notify(obj, 'newTimeStep', frost.Animator.TimeStepData(obj.currentTime, x));
obj.Draw(obj.currentTime, x);
obj.HandleAxis(obj.currentTime, x);
notify(obj, 'reachedEnd', frost.Animator.TimeStepData(obj.currentTime, x));
if obj.isLooping
if ~Freeze
obj.currentTime = obj.startTime;
end
else
obj.isPlaying = false;
end
else
x = GetData(obj, obj.currentTime);
notify(obj, 'newTimeStep', frost.Animator.TimeStepData(obj.currentTime, x));
obj.Draw(obj.currentTime, x);
obj.HandleAxis(obj.currentTime, x);
if ~Freeze
obj.currentTime = obj.currentTime + obj.TimerDelta*obj.speed;
end
end
end
end
methods
function HandleAxis(obj, t, x)
[center, radius, yaw] = GetCenter(obj, t, x);
if length(radius) == 1
axis(obj.axs, [center(1)-radius, center(1)+radius, center(2)-radius, center(2)+radius,center(3)-radius/3, center(3)+radius]);
else
axis(obj.axs, radius);
end
hAngle = 0;
vAngle = 0;
switch(obj.pov)
case frost.Animator.AnimatorPointOfView.North
hAngle = hAngle + 0;
case frost.Animator.AnimatorPointOfView.South
hAngle = hAngle + 180;
case frost.Animator.AnimatorPointOfView.East
hAngle = hAngle - 90;
case frost.Animator.AnimatorPointOfView.West
hAngle = hAngle + 90;
case frost.Animator.AnimatorPointOfView.Front
hAngle = hAngle + yaw;
case frost.Animator.AnimatorPointOfView.Back
hAngle = hAngle + 180 + yaw;
case frost.Animator.AnimatorPointOfView.Left
hAngle = hAngle - 90 + yaw;
case frost.Animator.AnimatorPointOfView.Right
hAngle = hAngle + 90 + yaw;
case frost.Animator.AnimatorPointOfView.TopSouthEast
hAngle = hAngle + 225;
vAngle = vAngle + 45;
case frost.Animator.AnimatorPointOfView.TopFrontLeft
hAngle = hAngle + 225 + yaw;
vAngle = vAngle + 45;
end
if obj.pov ~= frost.Animator.AnimatorPointOfView.Free
view(obj.axs, hAngle, vAngle);
end
end
function Draw(obj, t, x)
obj.display.update(x);
[center, radius, ~] = GetCenter(obj, t, x);
delete(obj.text);
obj.text = text(center(1)-radius/2,center(2),center(3)+radius-0.2,['t = ',sprintf('%.2f',t)]); %#ok<CPROPLC>
obj.text.FontSize = 14;
obj.text.FontWeight = 'Bold';
obj.text.Color = [0,0,0];
% set(obj.text);
drawnow;
end
function [center, radius, yaw] = GetCenter(obj, t, x)
center = [0,0,0];
radius = 3;
yaw = 0;
end
function x = GetData(obj, t)
t_start = obj.t_all(1);
t_end = obj.t_all(end);
delta_t = t_end - t_start;
if t < t_start || t > t_end
val = floor((t - t_start) / delta_t);
t = t - val * delta_t;
end
if t < t_start
t = t_start;
elseif t > t_end
t = t_end;
end
n = length(obj.t_all);
x = obj.x_all(:, 1); % Default
a = 1;
b = n;
while (a <= b)
c = floor((a + b) / 2);
if t < obj.t_all(c)
x = obj.x_all(:, c);
b = c - 1;
elseif t > obj.t_all(c)
a = c + 1;
else
x = obj.x_all(:, c);
break;
end
end
end
end
events
newTimeStep
playStateChanged
reachedEnd
end
end
|
function pdMat = randPD(n)
[u,~,~] = svd(rand(n,n));
pdMat = u * diag(rand(n,1)) * u';
|
% history points for smoothWavyWall
%
%-----------------------------------------------------%
% points
nx=10; % nx=number of x-points
ny=100; % ny=number of y points per x-location
h=0.50; % height to go up to in Y
casename='smoothWavyWall';
%-----------------------------------------------------%
% get x locations from maass
%
fil = 'maass/dat';
xM = zeros(1,nx);
for i=1:nx
nameM = [fil,num2str(i,'%0.2d')];
xM(i) = dlmread(nameM,'',[0 3 0 3]);
end
xM(end) = xM(end)-1;
x = xM + 2;
%-----------------------------------------------------%
% geometry
[x,y]=meshgrid(x,linspace(0,h,ny));
[x,y,xw,yw] = wavyWall(x,y,casename);
x = reshape(x,[nx*ny,1]);
y = reshape(y,[nx*ny,1]);
z = 0*x;
%-----------------------------------------------------%
% create file casename.his
format long
A = [x,y,z];
casename=[casename,'.his'];
fID = fopen(casename,'w');
fprintf(fID, [num2str(nx*ny) ' !=number of monitoring points\n']);
dlmwrite(casename,A,'delimiter',' ','-append');
type(casename)
|
% Reads multiple folders recorded on same/different days and produces
% matrix with all sessions and folders recorded
%
% Revision history:
%
% v1.0 September 1, 2016. Basic script prepared.
% Data file is format:
% [subjectName_Date_chChannelNumber_uUnitNumber_unitType.mat]
% (for example: aq_20161231_ch1_u1_m.mat);
function [y] = get_path_spikes_v10 (path1, subject_name)
% Determine how many files with the subject name are there
index_cur_dir = dir(path1);
% Initialize output variables
temp_ind_subj = cell(length(index_cur_dir), 1);
temp_ind_dates = NaN(length(index_cur_dir), 1);
temp_ind_channels = NaN (length(index_cur_dir), 1);
temp_ind_units = NaN (length(index_cur_dir), 1);
temp_ind_unit_class = cell (length(index_cur_dir), 1);
%% Parse the file name
% Temporary variables initiated
fnames = cell (length(index_cur_dir), 1); % Temporary file name used
fdates = cell (length(index_cur_dir), 1); % Dates in string format will be stored here
% Extract file names & their sizes
for i=1:length(index_cur_dir)
fnames{i} = index_cur_dir(i).name;
end
%============
% Subject names
%============
% Extract subject names
for i=1:length(fnames)
if length(fnames{i}) > length(subject_name)
if strcmp(fnames{i}(1:length(subject_name)), subject_name)
temp_ind_subj{i} = subject_name; % Save subject name
fnames{i}(1:length(subject_name)) = [];
else
temp_ind_subj{i} = NaN; % Save subject name
fnames{i} = NaN;
end
else
temp_ind_subj{i} = NaN;
fnames{i}=[]; % Discard if folder doesnt start with subject name
end
end
% If there is a dash, extract it
for i=1:length(fnames)
if length(fnames{i}) > 1
if strcmp(fnames{i}(1), '_')
fnames{i}(1) = [];
end
end
end
%===============
% Date detection
%===============
% Detect chanel number
for i=1:length(fnames)
if length(fnames{i}) >= 2
[a,b] = strsplit(fnames{i}, '_'); % Find delimiter
if ~isempty(b) % If delimiter exists
if str2num(a{1})
temp_ind_dates(i) = str2num(a{1});
fnames{i}(1:length(a{1})) = [];
else
temp_ind_dates(i)=NaN;
fnames{i}=NaN;
end
else
temp_ind_dates(i)=NaN;
fnames{i} = NaN;
end
end
end
% If there is a dash, extract it
for i=1:length(fnames)
if length(fnames{i}) > 1
if strcmp(fnames{i}(1), '_')
fnames{i}(1) = [];
end
end
end
%=================
% Channel detection
%=================
% Detect if next is channel notation
for i=1:length(fnames)
if length(fnames{i}) >= 2
if strcmp(fnames{i}(1:2), 'ch')
fnames{i}(1:2) = [];
else
fnames{i}=NaN;
end
else
fnames{i} = NaN;
end
end
% Detect chanel number
for i=1:length(fnames)
if length(fnames{i}) >= 2
[a,b] = strsplit(fnames{i}, '_'); % Find delimiter
if ~isempty(b) % If delimiter exists
if str2num(a{1})
temp_ind_channels(i) = str2num(a{1});
fnames{i}(1:length(a{1})) = [];
else
temp_ind_channels(i) = NaN;
fnames{i}=NaN;
end
else
temp_ind_channels(i) = NaN;
fnames{i} = NaN;
end
end
end
% If there is a dash, extract it
for i=1:length(fnames)
if length(fnames{i}) > 1
if strcmp(fnames{i}(1), '_')
fnames{i}(1) = [];
end
end
end
%=================
% Unit detection
%=================
% Detect if next is unit number notation
for i=1:length(fnames)
if length(fnames{i}) >= 1
if strcmp(fnames{i}(1), 'u')
fnames{i}(1) = [];
else
fnames{i}=NaN;
end
else
fnames{i} = NaN;
end
end
% Detect unit number
for i=1:length(fnames)
if length(fnames{i}) >= 2
[a,b] = strsplit(fnames{i}, '_'); % Find delimiter
if ~isempty(b) % If delimiter exists
if str2num(a{1})
temp_ind_units(i) = str2num(a{1});
fnames{i}(1:length(a{1})) = [];
else
temp_ind_units(i) = NaN;
fnames{i}=NaN;
end
else
temp_ind_units(i) = NaN;
fnames{i} = NaN;
end
end
end
% If there is a dash, extract it
for i=1:length(fnames)
if length(fnames{i}) > 1
if strcmp(fnames{i}(1), '_')
fnames{i}(1) = [];
end
end
end
%=================
% Unit classification detection
%=================
for i=1:length(fnames)
if length(fnames{i}) >= 1
if strcmp(fnames{i}(1), 'u') || strcmp(fnames{i}(1), 's') || strcmp(fnames{i}(1), 'm')
temp_ind_unit_class{i}(1) = fnames{i}(1);
fnames{i}(1) = [];
else
temp_ind_unit_class{i}(1) = NaN;
fnames{i}=NaN;
end
else
temp_ind_unit_class{i}(1) = NaN;
fnames{i} = NaN;
end
end
%% For each date and session prepare a list of paths
% Find unique days used
unique_dates = unique(temp_ind_dates);
ind=isnan(unique_dates); unique_dates(ind)=[];
index_cur_dir; % This is necessary input. Contains all file names and file ordering
% Create output matrix
file_name1 = cell(1);
dates1 = [];
subject1 = cell(1);
unit1 = [];
channel1 = [];
unit_class1 = cell(1);
path_temp1 = cell(1);
for i=1:length(unique_dates)
index1 = find(temp_ind_dates == unique_dates(i));
for j=1:length(index1);
if length(file_name1)==1 && isempty(file_name1{1})
ind = 1;
else
ind = ind+1;
end
file_name1{ind,1} = index_cur_dir(index1(j)).name;
dates1(ind,1) = temp_ind_dates(index1(j));
subject1{ind,1} = temp_ind_subj{index1(j)};
unit1(ind,1) = temp_ind_units(index1(j));
channels1(ind,1) = temp_ind_channels(index1(j));
unit_class1{ind,1} = temp_ind_unit_class{index1(j)};
path_temp1{ind,1} = [path1, index_cur_dir(index1(j)).name];
end
end
%% Output
y.index_dates=dates1;
y.index_unique_dates = unique_dates;
y.index_subjects = subject1;
y.index_file_name = file_name1;
y.index_unit = unit1;
y.index_channel = channels1;
y.index_unit_type = unit_class1;
y.index_path = path_temp1;
|
function summary=SG_analyse_bootstrap(N,restricted)
if nargin==0
N = 1000 ;
end
%nDS = numel(dir(sprintf('../results/bootstrap/data*_r%d.mat',restricted)))/45 ;
nDS = 100;%
%effect_types = {'dynamics','choiceUpdate','successUpdate','forceUpdate'};
% for each random group
parfor iB=1:N
rng('shuffle');
% draw 18 random subjects
dummy_group = randperm(nDS,18);
%load data
[summary_group]=SG_analyse('bootstrap',restricted,dummy_group);
summary_sub(iB) = summary_group ;
end
summary.all = summary_sub;
% for iT=1:numel(effect_types)
%
% MC = [summary_sub.MC];
%
% Ef = struct.extract([MC.(effect_types{iT})],'Ef');
% xp = struct.extract([MC.(effect_types{iT})],'xp');
%
% summary.(effect_types{iT}).Ef_mean = mean(Ef);
% summary.(effect_types{iT}).Ef_std = std(Ef);
%
% summary.(effect_types{iT}).xp_mean = mean(xp);
% summary.(effect_types{iT}).xp_std = std(xp);
%
% end
%
% effect_param = fields(summary_sub(1).BMA.significance);
% for iT=1:numel(effect_param)
% BMA = [summary_sub.BMA];
%
% pp = struct.extract([BMA.significance],effect_param{iT}) ;
% summary.(effect_param{iT}).p_mean = mean(pp);
% summary.(effect_param{iT}).p_std = std(pp);
%
% val = struct.extract([BMA.effects],effect_param{iT}) ;
% summary.(effect_param{iT}).val_mean = mean(val);
% summary.(effect_param{iT}).val_std = std(val);
% end
|
%% *_Branin Function_*
%
% Syntax:
% Y = UQ_BRANIN(X)
% Y = UQ_BRANIN(X,P)
%
% The model contains M=2 (independent) random variables (X=[X_1,X_2])
% and 6 scalar parameters of type double (P=[a,b,c,r,s,t]).
%
% Input:
% X N x M matrix including N samples of M stochastic parameters
% P vector including parameters
% by default: a = 1; b = 5.1/(2*pi)^2; c = 5/pi; r = 6; s = 10;
% t = 1/(8*pi);
%
% Output/Return:
% Y column vector of length N including evaluations using branin
% function
%
%%%
function Y = uq_branin(X,P)
%% Check
%
narginchk(1,2)
assert(size(X,2)==2,'only 2 input variables allowed')
%% Evaluation
%
% $$f(\mathbf{x}) = a(x_2 - bx_1^2 + cx_1 - r)^2 +s(1-t)\cos(x_1) +s$$
%
if nargin==1
% Constants
a = 1;
b = 5.1/(2*pi)^2;
c = 5/pi;
r = 6;
s = 10;
t = 1/(8*pi);
Y = a*(X(:,2) - b*X(:,1).^2 + c*X(:,1) - r).^2 + s*(1-t)*cos(X(:,1)) + s;
end
if nargin==2
Y = P(1)*(X(:,2) - P(2)*X(:,1).^2 + P(3)*X(:,1) - P(4)).^2 + P(5)*(1-P(6))*cos(X(:,1)) + P(5);
end
end
|
function varargout = colorSelector(varargin)
% COLORSELECTOR MATLAB code for colorSelector.fig
% COLORSELECTOR, by itself, creates a new COLORSELECTOR or raises the existing
% singleton*.
%
% H = COLORSELECTOR returns the handle to a new COLORSELECTOR or the handle to
% the existing singleton*.
%
% COLORSELECTOR('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in COLORSELECTOR.M with the given input arguments.
%
% COLORSELECTOR('Property','Value',...) creates a new COLORSELECTOR or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before colorSelector_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to colorSelector_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help colorSelector
% Last Modified by GUIDE v2.5 25-Aug-2019 19:52:32
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @colorSelector_OpeningFcn, ...
'gui_OutputFcn', @colorSelector_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before colorSelector is made visible.
function colorSelector_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to colorSelector (see VARARGIN)
% Choose default command line output for colorSelector
handles.output = hObject;
handles.choose = [0, 0, 0];
imshow(ones(500,500,3))
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes colorSelector wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = colorSelector_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
colorImage =ColorImage(10,10,50,50,[1,1, 0]);
colorImage.setChoose(handles.choose);
%gca(handles.axes1);
colorImage.plot(true);
handles.colorImage = colorImage;
guidata(hObject, handles);
% --- Executes on button press in checkboxRed.
function checkboxRed_Callback(hObject, eventdata, handles)
% hObject handle to checkboxRed (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
choose = handles.choose;
choose(1) = get(hObject, 'Value');
handles.colorImage.setChoose(choose);
if(any(choose))
handles.colorImage.plot(false);
else
handles.colorImage.plot(true);
end
handles.choose = choose;
guidata(hObject, handles);
% Hint: get(hObject,'Value') returns toggle state of checkboxRed
% --- Executes on button press in checkboxGreen.
function checkboxGreen_Callback(hObject, eventdata, handles)
% hObject handle to checkboxGreen (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
choose = handles.choose;
choose(2) = get(hObject, 'Value');
handles.colorImage.setChoose(choose);
if(any(choose))
handles.colorImage.plot(false);
else
handles.colorImage.plot(true);
end
handles.choose = choose;
guidata(hObject, handles);
% Hint: get(hObject,'Value') returns toggle state of checkboxGreen
% --- Executes on button press in checkboxBlue.
function checkboxBlue_Callback(hObject, eventdata, handles)
% hObject handle to checkboxBlue (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
choose = handles.choose;
choose(3) = get(hObject, 'Value');
handles.colorImage.setChoose(choose);
if(any(choose))
handles.colorImage.plot(false);
else
handles.colorImage.plot(true);
end
handles.choose = choose;
guidata(hObject, handles);
% Hint: get(hObject,'Value') returns toggle state of checkboxBlue
|
ps = ProcessDays(psparse,'IntraGroup','Cells',ndresp.SessionDirs,'AnalysisLevel','AllIntraGroup');
InspectGUI(ps)
figure; plot(ps)
% compare mean lifetime sparseness and median population sparseness
load sparsityobjs
% get indices grouped according to site
gind = groupDirs(sparseframe);
% find sites with more than 1 cell since we need more than 1 cell to
% compute population sparseness
si = find(sum(~isnan(gind))>1)
gind2 = gind(:,si);
% get the sparseness data grouped according to site
gdata = nanindex(sparseframe.data.sparsity,gind2)
% find mean sparseness for each site
gm = nanmean(gdata)
pm = prctile(ps.data.psparse,50);
% compute spree plot
% first compute variance for each cell
sfv = sparseframe.data.Values;
sv = nanstd(sfv).^2;
% now get variance for each site
vdata = nanindex(sv,gind2);
% find maximum variance
mv = nanmax(vdata);
% normalize by maximum variance
vdata2 = flipud(sort(vdata ./ repmat(mv,size(vdata,1),1)));
% data for 50 responsive cells
plot([nan nan 0 1],vdata2(:,[1 3 4 10 13]),'go-','MarkerSize',16)
hold on
plot([nan 0 0.5 1],vdata2(:,[2 5 6 7 9 11 12]),'bo-','MarkerSize',16)
plot([0 0.33 0.66 1],vdata2(:,8),'ro-','MarkerSize',16)
hold off
% data for 88 single units
subplot(1,6,1)
plot([nan nan nan nan nan 0 1],vdata2(:,[2 4 5 11 15 18 20]),'kx-','MarkerSize',16)
set(gca,'TickDir','out','Box','off')
% hold on
subplot(1,6,2)
plot([nan nan nan nan 0 0.5 1],vdata2(:,[3 10 12 14 16 21]),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
subplot(1,6,3)
plot([nan nan nan 0 0.33 0.66 1],vdata2(:,[1 17 19]),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
subplot(1,6,4)
plot([nan nan 0 0.25 0.50 0.75 1],vdata2(:,[6 13]),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
subplot(1,6,5)
plot([nan 0 0.2 0.4 0.6 0.8 1],vdata2(:,9),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
subplot(1,6,6)
plot([0 0.16 0.33 0.5 0.66 0.83 1],vdata2(:,[7 8]),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
% compute the area for 50 responsive cells
vd2 = vdata2(:,[1 3 4 10 13]);
vd3 = vdata2(:,[2 5 6 7 9 11 12]);
vd4 = vdata2(:,8);
a2 = 0.5 * (vd2(4,:) + 1);
a3 = 0.5 * repmat(0.5,1,2) * (vd3(2:3,:) + vd3(3:4,:));
a4 = 0.5 * repmat(1/3,1,3) * (vd4(1:3,:) + vd4(2:4,:));
screarea = [a2 a3 a4];
mean(screarea)
std(screarea)
% compute the area for 88 single units
vd2 = vdata2(:,[2 4 5 11 15 18 20]);
vd3 = vdata2(:,[3 10 12 14 16 21]);
vd4 = vdata2(:,[1 17 19]);
vd5 = vdata2(:,[6 13]);
vd6 = vdata2(:,9);
vd7 = vdata2(:,[7 8]);
a2 = 0.5 * (vd2(7,:) + 1);
a3 = 0.5 * repmat(0.5,1,2) * (vd3(5:6,:) + vd3(6:7,:));
a4 = 0.5 * repmat(1/3,1,3) * (vd4(4:6,:) + vd4(5:7,:));
a5 = 0.5 * repmat(1/4,1,4) * (vd5(3:6,:) + vd5(4:7,:));
a6 = 0.5 * repmat(1/5,1,5) * (vd6(2:6,:) + vd6(3:7,:));
a7 = 0.5 * repmat(1/6,1,6) * (vd7(1:6,:) + vd7(2:7,:));
screarea = [a2 a3 a4 a5 a6 a7];
mean(screarea)
std(screarea)
% compute scree plots by first normalizing each cell to its mean so that we
% can compare the variances across sites
% create normalized scree plot
sm = nanmean(sfv);
% normalize the spike counts by the mean so the variances
% between sites are equivalent
sfv2 = sfv ./ repmat(sm,size(sfv,1),1);
sv2 = nanstd(sfv2).^2;
% now get variance for each site
vdata3 = nanindex(sv2,gind2);
% find maximum variance
mv2 = nanmax(vdata3);
% normalize by maximum variance
vdata4 = flipud(sort(vdata3 ./ repmat(mv2,size(vdata3,1),1)));
% plot for 50 responsive cells
plot([nan nan 0 1],vdata4(:,[1 3 4 10 13]),'k:')
hold on
plot([nan 0 0.5 1],vdata4(:,[2 5 6 7 9 11 12]),'k--')
plot([0 0.33 0.66 1],vdata4(:,8),'k-')
hold off
% plot for 88 single units
subplot(1,6,1)
plot([nan nan nan nan nan 0 1],vdata4(:,[2 4 5 11 15 18 20]),'kx-','MarkerSize',16)
set(gca,'TickDir','out','Box','off')
% hold on
subplot(1,6,2)
plot([nan nan nan nan 0 0.5 1],vdata4(:,[3 10 12 14 16 21]),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
subplot(1,6,3)
plot([nan nan nan 0 0.33 0.66 1],vdata4(:,[1 17 19]),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
subplot(1,6,4)
plot([nan nan 0 0.25 0.50 0.75 1],vdata4(:,[6 13]),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
subplot(1,6,5)
plot([nan 0 0.2 0.4 0.6 0.8 1],vdata4(:,9),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
subplot(1,6,6)
plot([0 0.16 0.33 0.5 0.66 0.83 1],vdata4(:,[7 8]),'kx-','MarkerSize',16)
set(gca,'YTickLabel','','TickDir','out','Box','off')
% compute the area for 50 responsive cells
vd2a = vdata4(:,[1 3 4 10 13]);
vd3a = vdata4(:,[2 5 6 7 9 11 12]);
vd4a = vdata4(:,8);
a2a = 0.5 * (vd2a(4,:) + 1);
a3a = 0.5 * repmat(0.5,1,2) * (vd3a(2:3,:) + vd3a(3:4,:))
a4a = 0.5 * repmat(1/3,1,3) * (vd4a(1:3,:) + vd4a(2:4,:))
screarea2 = [a2a a3a a4a];
mean(screarea2)
std(screarea2)
% compute the area for 88 single units
vd2a = vdata4(:,[2 4 5 11 15 18 20]);
vd3a = vdata4(:,[3 10 12 14 16 21]);
vd4a = vdata4(:,[1 17 19]);
vd5a = vdata4(:,[6 13]);
vd6a = vdata4(:,9);
vd7a = vdata4(:,[7 8]);
a2a = 0.5 * (vd2a(7,:) + 1);
a3a = 0.5 * repmat(0.5,1,2) * (vd3a(5:6,:) + vd3a(6:7,:));
a4a = 0.5 * repmat(1/3,1,3) * (vd4a(4:6,:) + vd4a(5:7,:));
a5a = 0.5 * repmat(1/4,1,4) * (vd5a(3:6,:) + vd5a(4:7,:));
a6a = 0.5 * repmat(1/5,1,5) * (vd6a(2:6,:) + vd6a(3:7,:));
a7a = 0.5 * repmat(1/6,1,6) * (vd7a(1:6,:) + vd7a(2:7,:));
screarea2 = [a2a a3a a4a a5a a6a a7a];
mean(screarea2)
std(screarea2)
|
function [dat] = mainFrequencyAnalysis(dat);
%H1 Line -- loop to calculate on frequency analysis on a structure array
%Help Text --
%input requirements: dat is a structure array (output of impHYDAT)
%
%output details: dat, is the same arry entered in output with a filed that
% contain the frequency analysis. The analysis is run for
% each flow station.
%Author: Laurence Chaput-Desrochers
%date:august 19th 2013
%**************************************************************************
nbFiles = size(dat,1);
%compute log-PearsonIII frequency analysis
%**************************************************************************
for n = 1:nbFiles;
[out,tableN] = logPearsonIIIgeV2(dat(n,1).discharges,dat(n,1).year);
dat(n,1).freqDataPearson = tableN;
dat(n,1).logPearsonIII = out;
clear out tableN
end%end loop n
clear n
%**************************************************************************
end%end of function mainFrequancyAnalysis
|
function [ret] = showPossible(i_x, i_y)
global board;
thisPiece = board(i_x,i_y).possible;
thisPiece(isnan(thisPiece)) = 0;
ret = thisPiece;
end
|
%Author : Vignesh Waren Sunder
%Signal Digitisation and Reconstruction
%Coded using MATLAB R2019a- academic use
%GitHub: vicky-ML
close all
clc
%Generating Signal
t = 0:0.001:2; % set the time domain range (1 to 2 with 1000 steps)
f1 = 6;
f2 = 9;
x = sin(2*pi*f1*t)+sin(2*pi*f2*t); %Sanalog
figure
subplot(211)
plot(t,x);
title("Sanalog")
xlabel("Time(s)");
Fs = 100; %Our Sampling Frequency
Ts = 1/Fs;
n = 0:Ts:2; %set the time domain range
x_sampled= sin(2*pi*f1*n)+sin(2*pi*f2*n); %Ssam
subplot(212)
stem(n,x_sampled,'fill');
title("Ssam");
xlabel("Time(s) Fs=100Hz");
%Quantisation
maxx= max(x_sampled); %max value of Ssam
minn = min(x_sampled); % min value of Ssam
range = (maxx-minn)/16; % getting range with appropriate quatisation level
%we perform "for" loop to get the y_axis value for each step in x_axis and
%then round it to the nearest integer
for n1 = 1:length(x_sampled)
x_quant=round((x_sampled-minn)/range)*range+minn;
end
%Signal to quantisation noise ratio
powerinsig = x_sampled.^2; %Power in Signal
powerinnoise = (x_sampled-x_quant).^2; %Power in Noise
sqnr = 10*log10 (powerinsig/powerinnoise); %SQNR
figure
plot(t,x);
hold
stairs(n,x_quant)
title('Quantised')
xlabel("Time(s)");
%fft
%The value of Fs changes. Fs=100 for FFT of Ssamp | Fs=1000 for FFT of
%Sanalog. Kindly change the value when running the code.
xft = fft(x_sampled(1:length(x_sampled)-1)); %perform fft with a point delay(-1)
arr=0:Fs/(2*Fs):Fs-Fs/(2*Fs); %To get the range of the frequency spectrum
%(arr is 0 to 200 with 2000 steps) gives for one cycle
%We generated and plotted Frequency spectrum only for One Cycle so that we
%can easily perform FFTShift and extract the required frequency component
xabs=abs(xft); %gives the magnitude
figure
subplot(211)
plot(arr,xabs/Fs)
title('FFT of Sanalog')
xlabel("Frequency(Hz)");
ylabel("Magnitude");
xxftshift = fftshift(xft); %perform FFTShift
subplot(212)
plot(arr-0.5*Fs, abs(xxftshift)/Fs)%plot fftshift with desired range
title("FFTShift of Sanalog");
xlabel("Frequency(Hz)");
ylabel("Magnitude");
%Low Pass Filter
lpfilter = zeros (1,length(xxftshift)); %zero magnitude for this range
for number1 = 1:length(xxftshift) %magnitude is 1 for these range of points
if number1< 0.5*length(xxftshift)
lpfilter(number1)=1;
end
end
figure
plot(arr,xabs/Fs.*lpfilter) %perform cyclic convolution by using point wise
%multiplicaiton in Frequency domain. The required frequency signal is
%extracted
title("filtered spectrum Sanalog");
xlabel("Frequency(Hz)");
ylabel("Magnitude");
figure
iff = ifft(xft/Fs.*lpfilter*2); %perform ifft with extracted signal from
%the lpfilter
%iff = ifft(xft/Fs);
plot(n(1:length(n)-1),iff*Fs, 'r') %Plot the reconstructed Signal
hold
%stem(n,x_sampled,'fill'); %to get a stemed reconstructed signal output
%hold
plot(t,x, 'k')
title("Reconstructed Signal and Sanalog")
xlabel("Time (s)");
ylabel("Amplitude");
|
clc
clear all;
close all;
global epsilon;
global p;
%ep = 0.001;
eps = linspace(3,3,1);
iter = linspace(1,1,1);
epsilon = 0.01;
op = odeset('reltol',1e-9,'abstol',1e-11);
for i=iter
figure(i)
hold on;
p=eps(i);
epsilon = 0.1/(p^3)
val = epsilon*(p^3)
[t,y] = ode45('mms2d',[0,1000],0.01,op);
plot(t,y,'DisplayName','p ='+string(p));
mean(y)
%[t,y] = ode45('mms2d_avg',[0,400],0.01,op);
%plot(t,y,'DisplayName','p_avg ='+string(p),'linewidth',2);
%hold off;
title('$\epsilon$ = '+string(epsilon),'interpreter','latex')
xlabel('t')
ylabel('x')
legend
end
|
function h = mrpln02b_PlotPairwiseFactorsInFG(fg, values, plot_flags)
factor_color = plot_flags.factor_color;
factor_line_width = plot_flags.factor_line_width;
factor_linestyle = plot_flags.factor_linestyle;
h = []; odometryPathXCoords = []; odometryPathYCoords = [];
for i=0:double(fg.size)-1
if ~fg.exists(i), continue; end
f = fg.at(i);
keys = f.keys();
delta = abs(double(gtsam.mrsymbolIndex(keys.front()))-double(gtsam.mrsymbolIndex(keys.back())));
if delta == 1
% continue; % skip odometry factors for better visibility
factor_linestyle = '-';
else
continue % skip LC factors
factor_linestyle = '--';
end
edge = mrpln02c_PlotPairwiseFactor(f, values, factor_color, factor_line_width, factor_linestyle);
h = [h edge];
if delta == 1
odometryPathXCoords = [odometryPathXCoords edge.XData];
odometryPathYCoords = [odometryPathYCoords edge.YData];
hold on; plot(edge.XData, edge.YData, 'Color', plot_flags.factor_color, 'LineWidth', plot_flags.factor_line_width+2)
end
end
hold on; plot(odometryPathXCoords, odometryPathYCoords, '.', 'Color', plot_flags.factor_color, 'MarkerSize', 30) % mark observation poses
|
function second = Q_ra(x_1,x_1_r,x_2,x_2_r,P_a,P_b)
% Eq. 4 in Ref.[2]
second=P_b*(x_2-x_2_r)/((x_1-x_1_r+P_a*(x_2-x_2_r))^2+(P_b*(x_2-x_2_r))^2);
end
|
%NAME: Jadeja Jaydevsinh G.
%ROLL NO: 12MEC08
%BATCH: ME-2nd sem,2013
%DEPARTMENT: Electronics & Communication.
%SUBJECT: ADC
%1.Aim: To verify the nyquist theoram.
close all;
clear all;
t=-10:0.01:10;
T=8;
fm=1/T;
x=sin(2*pi*fm*t);
subplot(311);plot(t,x);
n=-10:1:10;
j=ones(1,length(n));
subplot(312);stem(n,j);axis([-10 10 0 2]);
xn=sin(2*pi*n*fm);
subplot(313);stem(n,xn);hold on;plot(n,xn);
|
%% This code is the code of the part 3
%% Calcul of matrix Ks and Ms
% function Part3(Samcef)
close all
run Dimensions
run Geometry
nElementT = 0;
for i = 1 : 45
nElementT = nElementT + element(i,5);
end
nodeList = zeros(nElementT,3);
basic_dofs = zeros(29,6);
for i = 1:29
basic_dofs(i,:) = [(i-1)*6+1 (i-1)*6+2 (i-1)*6+3 (i-1)*6+4 (i-1)*6+5 (i-1)*6+6];
end
nBeamG = 12; % number of big beams
nBeamM = 29; % number of middel beams
nBeamP = 4; % number of little beam
for i = 1:45
dofList(((i-1)*element(i,5))+1,:) = basic_dofs(element(i,1),:);
nodeList(((i-1)*element(i,5))+1,:) = Node(element(i,1),:);
for j = 1:element(i,5)-2
dofList((element(i,5)*(i-1))+1+j,:) = (29*6+((i-1)*(element(i,5)-2)+j-1)*6)+(1:6);
nodeList((element(i,5)*(i-1))+1+j,:) = Node(element(i,1),:) + ((Node(element(i,2),:)-Node(element(i,1),:))./(element(i,5)-1)*j);
end
dofList((i*element(i,5)),:) = basic_dofs(element(i,2),:);
nodeList((i*element(i,5)),:) = Node(element(i,2),:);
end
for i = 1:45
for j = 1:element(i,5)-1
Kel(:,:,(i-1)*(element(i,5)-1)+j) = matriceRaideur(element(i,3), element(i,4), nodeList((i-1)*element(i,5)+j,:), nodeList((i-1)*element(i,5)+(j+1),:));
Mel(:,:,(i-1)*(element(i,5)-1)+j) = matriceMasse(element(i,3), element(i,4), nodeList((i-1)*element(i,5)+j,:), nodeList((i-1)*element(i,5)+(j+1),:));
end
end
% Assembly of the structural and mass matrices
nNode = 0;
for i = 1 : 45
nNode = nNode + element(i,5) - 2;
end
nNode = nNode + 29;
Ks = zeros(nNode*6,nNode*6);
Ms = zeros(nNode*6,nNode*6);
for i = 1:45
for j = 1:element(i,5)-1
dofs1 = dofList((i-1)*element(i,5)+j,:);
dofs2 = dofList((i-1)*element(i,5)+(j+1),:);
locel = [dofs1 dofs2];
for k=1:12
for l=1:12
Ks(locel(k), locel(l)) = Ks(locel(k), locel(l)) + Kel(k,l,(i-1)*(element(i,5)-1)+j);
Ms(locel(k), locel(l)) = Ms(locel(k), locel(l)) + Mel(k,l,(i-1)*(element(i,5)-1)+j);
end
end
end
end
fixedDof = [10*6+1:10*6+6 11*6+1:11*6+6 12*6+1:12*6+6 13*6+1:13*6+6];
Ks(fixedDof, :) = [];
Ks(:, fixedDof) = [];
Ms(fixedDof, :) = [];
Ms(:, fixedDof) = [];
nb_vp = 10; % nombre de modes propres et valeurs propres à afficher
clear Ms
clear Ks
Ms = [1 0; 0 1]
Ks =[20000 -10000; -10000 20000]
C = [3 -1; -1 3];
[V, D]=eigs(Ks, Ms, 2, 'sm');
w = sqrt(diag(D)); % [rad/s]
f = w /2/pi;
V2 = V;
%% Calcul of parameters
A = zeros(2, 2);
epsR = zeros(2,1);
epsR(:,1) = 0.005;
result = zeros(2,1);
gamma = zeros(2,1);
mu = zeros(2,1);
V2t = V2';
omega = 2*pi;
result = A\epsR;
%C = result(1)*Ks + result(2)*Ms;
%% Codes
run ComparisonStep
run ComparisonSamcef
run FRF
|
% Marco Bettiol - 586580 - BATCH SIZE ESTIMATE
%
% CBT Simple Test
%
% This script implements a simulation of the estimate obtained
% using CBT in a batch of size n.
%
% Nodes are initially uniformily picked-up in the interval [0,1)
clear all;
close all;
clc;
n=16; % batch size
disp(['Size :' int2str(n)]);
nodes=rand(n,1);
% virtual node with value 1 to get easier search algorithm
% among the nodes
% asc sorting
nodes=[sort(nodes); 1];
if (n<2)
error('BRA must start with a collision');
end
% CBT Simulation
% true if we got a success in the last transmission
lastwassuccess=false;
%false to end CBT
waitforconsecutive=true;
imax=length(nodes); %index of the first node in the batch
imin=1; % index of the first node in the batch
xmin=0; % starting interval [0,1/2)
xlen=1/2; % we suppose a collision already occurred.
while (waitforconsecutive)
[e,imin,imax]=cbtsplit(nodes,imin,imax,xmin,xlen);
% update next analyzed interval
if(e==1)
xmin=xmin+xlen;
%xlen=xlen;
elseif (e==0)
xmin=xmin+xlen;
xlen=xlen/2;
else
%xmin=xmin;
xlen=xlen/2;
end
if (lastwassuccess==true && e==1)
disp(' ');
disp('CBT completed :');
disp(['Estimate :' num2str(1/xlen)]);
disp(['Last node transmitting :' int2str(imin-1)]);
waitforconsecutive=false;
end
if(e==1)
lastwassuccess=true;
else
lastwassuccess=false;
end
end
% DEBUG
% estimate is given by the first serie of descending differences in the
% nodes ID's
dif=-1*ones(n-1,1); %negative init
for i=1:n-1
dif(i)=nodes(i+1)-nodes(i);
end
nodes
dif
|
function [A,X,res] = DN_NMF(Y,opts)
%function [A,X,res] = nmf_qp_cg(Y,A,X,MaxIter,tol_c,lambda)
% The Damped Newton (DN) algorithm developed by
% Copyrirght R. Zdunek, A.-H. Phan, and A. Cichocki
%
% DN
%% line 61 is changed
defopts = struct('NumOfComp',[],'A0',[],'X0',[],'MaxIter',500,'Tol',1e-6,'lambda',1); % Theta maps checkStep.
if ~exist('opts','var')
opts = struct;
end
[r,A,X,MaxIter,tol_c,lambda] ...
=scanparam(defopts,opts);
if isempty(r)
r=size(Y,2);
end
[I,T] = size(Y);
epsil = eps;
Y = max(eps,Y);
n = 0; k = 0;
if isempty(A)
A=rand(I,r);
end
if isempty(X)
X=rand(r,T);
end
% Number of components
r = size(A,2);
% Scaling
da = sqrt(sum(A.^2,1))+eps;
A = bsxfun(@rdivide,A,da);
X = bsxfun(@times,da',X);
k = 0;
res = []; c = [];
while k < MaxIter
k = k + 1;
% if ~mod(k,50)
% disp(['Iteration: ',num2str(k)]);
% end
% UPDATES FOR A
% ======================================================================
% Memory prelocation
M = I*r;
Q = spalloc(M,M,M*r); Q_tilde = spalloc(M,M,M*r);
B = X*X'; C = X*Y';
Q = kron(speye(I),B); % Hessian of D(Y||AX) with respect to A
Qd = zeros(M,1);
At = A'; at = At(:); atp = at;
GAt = B*A' - C;
active = find((at <= epsil) & (GAt(:) > 0)); % active set
degradated = find((at <= epsil) & (abs(GAt(:)) < epsil), 1);
if ~isempty(degradated)
disp(['Degenerate: ',num2str(k)]);
end
inactive = setdiff(1:length(at),active); % inactive set
if ~isempty(active)
a_tilde = at; a_tilde(active) = 0;
c_tilde = C(:); c_tilde(active) = 0;
Q_tilde = Q;
Q_tilde(:,active) = 0; Q_tilde(active,:) = 0;
Qd(active) = 1;
Q_tilde = Q_tilde + spdiags(Qd,0,M,M) + lambda*speye(M);
else
a_tilde = at;
Q_tilde = Q + lambda*speye(M);
c_tilde = C(:);
end
% CGS
tol = 1e-6 + exp(-k);
at = zeros(M,1); Io = [];
Ao = setdiff(1:M,Io); Qd = zeros(M,1);
while ~isempty(Ao)
[a_tilde,FLAG,RELRES,ITER] = pcg(Q_tilde,c_tilde,tol);
Ao = find(a_tilde < 0);
Q_tilde(Ao,:) = 0; Q_tilde(:,Ao) = 0; Q_tilde = Q_tilde + spdiags(Qd,0,M,M);
c_tilde(Ao) = 0;
end
at = a_tilde;
At = (max(epsil,reshape(at,r,I)));
A = At';
da = eps+sqrt(sum(A.^2,1));
A = bsxfun(@rdivide,A,da);
X = bsxfun(@times,da',X);
% UPDATES FOR X
% ======================================================================
HX = A'*A + 1e-12*eye(r);
GX = HX*X - A'*Y;
I_active = find((X < eps)&(GX > 0));
UX = GX;
UX = HX\UX; UX(I_active) = 0;
X = max(eps,X - UX);
% Normalization
% da = eps+sqrt(sum(A.^2,1));
% A = bsxfun(@rdivide,A,da);
% X = bsxfun(@times,da',X);
%
dx = eps+sqrt(sum(X.^2,2));
X = bsxfun(@ldivide,dx,X);
A = bsxfun(@times,dx',A);
res(k) = norm(Y - A*X,'fro')/norm(Y,'fro');
% Stagnation breaking
if k > 3
c(k) = res(k-1) - res(k);
if (c(k)) < tol_c
lambda = lambda/2;
end
if k > 30 & c(k) < 0 & c(k-1) < 0 & c(k-2) < 0
break
end
end
end % while k
|
%clear
% ---------------------------------------------------------------------- %
% 実験設定。
% クエリ数を変更した際にはデータセットを新しく用意する必要があります。
% ---------------------------------------------------------------------- %
%実験名
exName = 'ex1204stl';
%実験日
todaysDate = datetime('now','TimeZone','local','Format','yMMd');
% iExperiment: 何周目の実験か。パラメータ設定以外では使用しない
for iExperiment = 1
% ---------------------------------------------------------------------- %
%フォルダ(outputフォルダ & mファイル)
[filepath, name, ext] = fileparts([mfilename('fullpath'),'.m']);
Dir_kume = filepath;
% モデルサイズの設定。有効な値は以下の通り。
% 16, 32, 40, 48, 56, 64, 80, 96
ModelSize = 40;
% モデルサイズの設定。任意の値が有効。
imgSize = 64;
% モデルタイプごとのクエリ数。基本5。
nQuery = 5;
% データセットを新しく用意するかどうか。
% true - 用意する/false - 用意しない
PrepareDataSet = false;
% クエリ・データベースのGeodesic sphereのID。
DatabaseGeodesicID = 6;
QueryGeodesicID = 6;
% Geodesic: ID(1 〜 7)に対応する投影枚数。
% 例:Geodesic IDが1のとき,投影枚数は12枚。
nProjections = [12, 42, 92, 162, 252, 362, 492];
% ssht: ID(1001 〜 1016) generated by 'makePrjPointList_SSHT(L)'
% mirror: ID(20XX)
% nProjections = [1, 6, 15, 28, 45, 66, 91, 120, 153, 190, 231, 276, 325, 378, 435, 496]
%
% 1次元投影: ID に '-(マイナス)' を付ける generated by 'makePrjPointList_projection1d(gdid)'
% 作成できた2次元投影を 'Projection1dFromProjection2d.m' に突っ込むと
% マイナスを付ける前の ID の頂点に対応した1次元投影を求められる
%
% クエリ・データベースの部分空間の使用次元数。
rDatabase = 6;
rQuery = 6;
% 特徴の高周波成分削減回数。
nDivide = 0;
% 結果を Excel に出力するためのパラメータ
% 【対象のExcelファイルは開じる(開いてると書き込めない)】
% 【MacOS,Linux は非対応, 可能なら代わりにCSVファイルで出力される】
% Excel ファイル名(拡張子 '.xlsx' 忘れずに。上書き注意!)
excelFileName = [exName, '_', char(todaysDate), '.xlsx'];
% シート番号
sheet = iExperiment;
% 書き込みを始めるセル
% 例:[5,2] -> 'B5' から書き始める
startCell = [1,1];
% 有効数字(Excelへの出力時、複素数のためにString型へ変換)
precision = 6;
% ---------------------------------------------------------------------- %
current_path = pwd;
cRetrieval = tic;
% モデルタイプの名称とモデルタイプの数。
% 基本的にはClutch, Die, Gearの3種類。
% TypeName = {'Clutch'; 'Die'; 'Gear';};
% TypeName = {'clutch'; 'die'; 'gear';};
TypeName = {'clutch'; 'die'; 'gear'; 'mould'; 'hydraulic';};
% TypeName = {'clutch'; 'die'; 'gear'; 'mould'; 'hydraulic'; 'pvb'; 'steamtrap'; 'swashplate'; 'clutch_die'; 'die_gear'; 'gear_mould'; 'mould_clutch'; 'clutch_8'; 'keo'; 'morton';};
nModelType = length(TypeName);
% 投影計算 & 処理時間計測
CulcProcessingTime_forSato(exName, DatabaseGeodesicID, QueryGeodesicID, imgSize, TypeName);
% 投影の統合
[QueryProjection,DatabaseProjection] = InteglatePrj_forSato(exName, DatabaseGeodesicID, QueryGeodesicID, imgSize, TypeName);
% %{
DatabaseName = fieldnames(DatabaseProjection);
QueryName = fieldnames(QueryProjection);
cDatabaseExtraction = tic;
% データベース側の特徴抽出処理
disp('データベース側の特徴抽出処理を実行中');
for iDatabase = 1 : length(DatabaseName)
tDatabaseProjection = DatabaseProjection.(DatabaseName{iDatabase});
% 投影画像の重み付け
DatabaseWeightedProjection = ...
WeightingProjection(tDatabaseProjection);
% 特徴抽出処理
DatabaseFeature.(DatabaseName{iDatabase}) = ...
DescriptorForMSM(DatabaseWeightedProjection, nDivide);
end
ExperimentTime.DatabaseExtraction = toc(cDatabaseExtraction);
fprintf('処理時間:%f[s]\n', ExperimentTime.DatabaseExtraction);
% データベース側の部分空間の生成
cDatabaseSubspace = tic;
disp('データベース側の部分空間生成処理を実行中');
for iDatabase = 1 : length(DatabaseName)
tDatabaseFeature = DatabaseFeature.(DatabaseName{iDatabase});
LabelList = fieldnames(tDatabaseFeature);
for iLabel = 1 : length(LabelList)
[tDatabaseSubspace] = ...
EVD(tDatabaseFeature.(LabelList{iLabel}), rDatabase);
DatabaseSubspace.(DatabaseName{iDatabase}).(LabelList{iLabel}) = ...
tDatabaseSubspace;
end
end
ExperimentTime.DatabaseSubspace = toc(cDatabaseSubspace);
fprintf('処理時間:%f[s]\n', ExperimentTime.DatabaseSubspace);
cQueryExtraction = tic;
% クエリ側の特徴抽出処理
disp('クエリ側の特徴抽出処理を実行中');
for iQuery = 1 : length(QueryName)
tQueryProjection = QueryProjection.(QueryName{iQuery});
% 投影画像の重み付け
QueryWeightedProjection = ...
WeightingProjection(tQueryProjection);
% 特徴抽出処理
QueryFeature.(QueryName{iQuery}) = ...
DescriptorForMSM(QueryWeightedProjection, nDivide);
end
ExperimentTime.QueryExtraction = toc(cQueryExtraction);
fprintf('処理時間:%f[s]\n', ExperimentTime.QueryExtraction);
% クエリ側の部分空間の生成
cQuerySubspace = tic;
disp('クエリ側の部分空間生成処理を実行中');
for iQuery = 1 : length(QueryName)
tQueryFeature = QueryFeature.(QueryName{iQuery});
LabelList = fieldnames(tQueryFeature);
for iLabel = 1 : length(LabelList)
[tQuerySubspace] = ...
EVD(tQueryFeature.(LabelList{iLabel}), rQuery);
QuerySubspace.(QueryName{iQuery}).(LabelList{iLabel}) = ...
tQuerySubspace;
end
end
ExperimentTime.QuerySubspace = toc(cQuerySubspace);
fprintf('処理時間:%f[s]\n', ExperimentTime.QuerySubspace);
Similarity = zeros(length(QueryName), length(DatabaseName)); % 各モデルとクエリとの類似度を格納する配列。
ExperimentTime.Matching = 0;
disp('モデル間の距離を相互部分空間法によって計算中');
for iQuery = 1 : length(QueryName)
tQuerySubspace = QuerySubspace.(QueryName{iQuery});
for iDatabase = 1 : length(DatabaseName)
tDatabaseSubspace = DatabaseSubspace.(DatabaseName{iDatabase});
% データベースモデルとの距離を計算
cMatching = tic;
LabelList = fieldnames(tQuerySubspace);
% 部分空間による距離計算
tSimilarity = 0;
for iLabel = 1 : length(LabelList)
U = tQuerySubspace.(LabelList{iLabel});
V = tDatabaseSubspace.(LabelList{iLabel});
tSimilarity = tSimilarity + MSM(U, V);
end
tSimilarity = tSimilarity / length(LabelList);
Similarity(iQuery, iDatabase) = tSimilarity;
ExperimentTime.Matching = ExperimentTime.Matching + toc(cMatching);
end
end
fprintf('処理時間:%f[s]\n', ExperimentTime.Matching);
% 正解率を算出する。
for iModelType = 1 : nModelType
TrueModelIndex = 5 * (iModelType - 1) + (1:5)';
TopIndex = nQuery * (iModelType - 1) + 1;
BottomIndex = nQuery * iModelType;
tSimilarity = Similarity(TopIndex : BottomIndex, :);
[~, MinIndex] = min(tSimilarity, [], 2);
Accuracy.(TypeName{iModelType}) = sum(MinIndex == TrueModelIndex) / nQuery;
end
ExperimentTime.Total = toc(cRetrieval);
fprintf('プログラム全体の処理時間:%f[s]\n', ExperimentTime.Total);
% 結果を構造体としてまとめる。
ExperimentResult.SimilarityMatrix = Similarity;
ExperimentResult.Accuracy = Accuracy;
ExperimentResult.ExperimentTime = ExperimentTime;
% データセットを構造体としてまとめる。
%DataSet.ShiftVector = ShiftVector;
%DataSet.RotateVector = RotateVector;
% 結果を保存する。
FileName = sprintf('Result_GDID_D%dQ%d_Query%d_%s', ...
DatabaseGeodesicID, QueryGeodesicID, nQuery, exName);
% save(FileName, 'ExperimentResult', 'DataSet');
save([Dir_kume, filesep, FileName], 'ExperimentResult');
% 結果を Excel にまとめる
bodyStruct = ExperimentResult; % output structure
headerStruct = struct;
headerStruct.exName = exName;
headerStruct.DatabaseGeodesicID = DatabaseGeodesicID;
headerStruct.QueryGeodesicID = QueryGeodesicID;
headerStruct.nQuery = nQuery;
headerStruct.matfile = [FileName,'.mat'];
savePath = [Dir_kume, filesep, excelFileName];
saveStructure(savePath,bodyStruct,headerStruct,startCell,sheet,precision);
% ---------------------------------------------------------------------- %
%}
end % for iExpetiment
|
function [ array_stddev, array_mean ] = my_stddev( one_dim_array )
% pusing bro, ada obat nyamuk?
% dapatkan panjang array
n_array = length(one_dim_array);
% dapatkan nilai mean
array_mean = my_mean(one_dim_array);
% dapatkan stddev kuadrat
stddev_sum = 0;
for i = 1:n_array
stddev_sum = stddev_sum+((one_dim_array(i)-array_mean)^2);
end
array_stddev = sqrt(stddev_sum/n_array);
end
|
%% A. Benchmark
ngrid=8361;
grouprankmtgppv7alls120g8361mars=zeros(ngrid,12);
for ns=1:ngrid
[transdat,lambda] = boxcox((senscoreMARSgppv7alls120g8361(ns,:)+1)');
Y = pdist(transdat);
Z = linkage(Y,'ward');
[~,T] = dendrogram(Z,4);
orimax=zeros(4,1);
for i=1:4
orimax(i,1)=max(transdat(find(T==i))');
end
[stmax,index]=sort(orimax);
tT=T;
for i=1:4
tT(find(T==index(i)),1)=5-i;
end
grouprankmtgppv7alls120g8361mars(ns,:)=tT;
end
% Group rank statistics
grouprankfreqgppv7alls120g8361=zeros(4,12);
for i=1:4
for j=1:12
for k=1:ngrid
if (grouprankmtgppv7alls120g8361mars(k,j)==i)
grouprankfreqgppv7alls120g8361(i,j)=grouprankfreqgppv7alls120g8361(i,j)+1;
end
end
end
end
finalgrouprankgppv7alls120g8361=zeros(1,12);
for i=1:12
finalgrouprankgppv7alls120g8361(i)=find(grouprankfreqgppv7alls120g8361(:,i)==max(grouprankfreqgppv7alls120g8361(:,i)));
end
finalgridportiongppv7alls120g8361=zeros(1,12);
for i=1:12
finalgridportiongppv7alls120g8361(i)=grouprankfreqgppv7alls120g8361(finalgrouprankgppv7alls120g8361(i),i)/ngrid;
end
|
%Q6*
function [image, correctLabel, predictedLabel] = PredictTest (n)
allTrainImages = loadMNISTImages('./train-images.idx3-ubyte');
allTrainLabels = loadMNISTLabels('./train-labels.idx1-ubyte');
mdl = fitcknn(allTrainImages', allTrainLabels);
allTestImages = loadMNISTImages('./t10k-images.idx3-ubyte');
allTestLabels = loadMNISTLabels('./t10k-labels.idx1-ubyte');
image = allTestImages(:, n);
predictedLabel = predict(mdl, image');
correctLabel = allTestLabels(n);
image = reshape(image, 28, 28);
end
|
function s = accuracy(x,y,value)
[ m, n ] = size(x);
if ( n != 1)
error('x is not a column vector');
endif
[ m, n ] = size(y);
if ( n != 1)
error('y is not a column vector');
endif
if (length(x) != length(y))
error('inputs column vectors x and y should have the same length');
endif
R = x >= value;
TP = sum(R.*y);
TN = sum((1-R).*(1-y));
s = (TP+TN)/m;
endfunction
|
function [ digit ] = FindDigit( I )
dir = 'letters/';
ext = '.bmp';
max_coeff = -2;
for i = 1:10
im = imread([dir sprintf('%d', i-1) ext]);
coeff = corr2(im, I);
if coeff > max_coeff
max_coeff = coeff;
digit = i-1;
end
end
end
|
function saveAsAvi_AI_ratio(matFilesPath, matFilesPrefix, aviFilesPath, aviFilesPrefix, ...
radius, nSides)
%% saving a video for changing activator/inhibitor levels
% in the colony.
files = dir([matFilesPath filesep matFilesPrefix '*.mat']);
nTimePoints = numel(files);
videoPath = [aviFilesPath filesep aviFilesPrefix '_' matFilesPrefix];
%%
fig = figure;
set(fig, 'Position', [68 800 500 400]);
fullVideoPath = [videoPath '.avi'];
v = VideoWriter(fullVideoPath); v.FrameRate = 5; open(v);
counter = 1;
for ii = 1:nTimePoints
outputFile = [matFilesPath filesep matFilesPrefix '_t' int2str(ii) '.mat'];
load(outputFile, 'storeStates');
if ii == 1 % get the colony boundary
nSquares = size(storeStates,1);
edgeLength = 1;
lattice = false(nSquares);
[~, ~, colonyState] = specifyColonyInsideLattice(lattice, radius, nSides);
[colonyEdgeIdx] = specifyRegionWithinColony(colonyState, edgeLength);
end
timeSteps = size(storeStates,4);
for kk = [1:timeSteps] % each file has multiple timesteps
activator = storeStates(:,:,1,kk);
inhibitor = storeStates(:,:,2,kk);
values = inhibitor./activator;
values(isnan(values)) = 0;
values = values.*colonyState;
imagesc(values); colorbar; caxis([0 5]);
title(['activator/inhibitor' 't=' int2str(counter)]);
counter = counter+1;
% if component == 1
% caxis([0 1.1]);
% elseif component < 3
% caxis([0 2.5]);
% else
% caxis([0 0.5]);
% end
hold on;
plot(colonyEdgeIdx(:,2), colonyEdgeIdx(:,1), 'k.', 'MarkerSize', 8); axis off;
drawnow;
pause(0.01);
M = getframe(fig);
writeVideo(v,M);
end
end
close(v);
end
|
clear
% For plotting
h = figure;
hold on;
grid on;
title('Earth temperature vs albedo');
xlabel('Temperature (K)');
ylabel('Albedo');
% Variables
alpha = 0; % Albedo - describes how much sunlight Earth reflects.
sigma = 5.67 * 1e-8; % Stefan-Boltzmann constant - total intensity.
I = 344; % Incident - short-wave radiation from the sun.
% Base function - balance between amount of emitted/absorbed energy:
% (1 - alpha) * I = sigma * T^4
% Case 1:
% When temperature on Earth is T1 = 235 K,
% then alpha is 0.5 (high albedo - there is ice and clouds reflecting sun).
alpha1 = 0.5;
T1_mean = nthroot((1-alpha1)*I/sigma, 4); % 234 K
line([200 250],[alpha1 alpha1],'LineWidth',1);
% Case 2:
% When temperature is between 250 and 270 K, then albedo has functional
% dependency of (270 - T) / 40. After solving balance equation and summing
% temperatures, then mean is 259 K.
T2 = 250:1:270;
alpha2 = (270 - T2) / 40;
syms T; % Define symbol for solving equation
eqnLeft = T; % Left side of equation
eqnRight = nthroot((1-(270 - T) / 40)*I/sigma, 4); % Right side of equation
initialGuess = 300; % Initial guess where solution converges to 260 K.
T_mean = vpasolve(eqnLeft == eqnRight, T, initialGuess); % 260 K
plot(T2, alpha2);
% Case 3:
% When temperature on Earth is T3 = 280 K,
% then alpha is 0 (low albedo - no ice and clouds reflecting sun).
alpha3 = 0;
T3_mean = nthroot((1-alpha3)*I/sigma, 4); % 279 K
line([270 300],[alpha3 alpha3],'LineWidth',1);
% Save plot to file
saveas(h, 'ex4','jpg');
% Summary:
% In first case average temperature is 234 K,
% in second case 259 K
% and in third case 279 K.
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4