Splitting a wav file in Matlab - matlab

I previously asked a question, which is related to my actual problem. I converted a mp3 file to a wav file, by using the program audacity. Th duration of the wav-file is about 10 seconds. I want to split it in 10 parts, which means, each part takes 1 second. How can i make it happen? Please apologize my ignorance, even though the community provided me some answer.
[y,fs]=wavread('UnchainMyHeart');
t=linspace(0,length(y)/fs,length(y));
plot(t,y)
The code here, shows my wav file in the time domain, but you probably can't see it, since you don't have the wav file. Doesn't matter. Now, is it possibly to continue from there, concering my question? I believe it has somthing to do with matrix...
Unfortunatley I lack the knowledge, therefore I always appreciate your help!

It depends on what you want to do next. The easiest way to get part of signal is:
part=y(1:Fs);
you probaly want array of this things so use FOR, or WHILE sructure, smth like this:
%in loop
part(i)=(i*Fs:i*Fs+Fs);
i=i+1;
be aware of array length

Here is a WavReader.m class which reads wav in chunks of the same length.
To read 1-second chunks, use it like this:
wr = WavReader('c:/wavs/killyourmama.wav');
wr.SetChunkLengthInMiliSeconds( 1000.0 );
while(true)
[pcm, num_read] = wr.ReadChunk();
if( num_read==0 ); break; end;
fprintf('Progress: %5.2f%%\n', wr.Progress() );
end
Here is the class:
classdef WavReader < handle
%WavReader Reads wav files in chunks
% Flexible wav chunk reader.
%
% 1) Usage steps in case of full file read:
%
% Create wav reader:
% wr = WavReader(path);
% Read all samples:
% [samples, count] = GetAllSamples();
%
% 2) Usage steps in case of range read:
%
% Create wav reader:
% wr = WavReader(path);
%
% Read samples from within a range:
% [samples, count] = GetSamples(seconds_start, seconds_finish);
%
% 3) Usage steps in case chunk-by-chunk read:
%
% Create wav reader:
% wr = WavReader(path);
%
% Set range of interest:
% wr.SetRange( seconds_start, seconds_finish );
%
% Set chunk size you want to read:
% wr.SetChunkLength( chunk_size );
%
% Read chunk-by-chunk:
% while(num_read)
% [pcm, num_read] = wr.ReadChunk();
%
%
properties (Access=private)
% Info
path;
fs;
total_samples;
total_seconds;
% Range of interest
range_length;
range_samples;
% Current state of chunks
chunk_length;
total_chunks;
chunks_read;
end
methods
function obj = WavReader( in_path_wav )
% Constructor
try
obj.path = in_path_wav;
info = audioinfo(obj.path);
obj.fs = info.SampleRate;
obj.total_samples = info.TotalSamples;
obj.total_seconds = info.Duration;
catch
error('Problem with opening wav file. Exiting.')
end
% Defaul reads full range, whole file.
obj.SetRangeFull();
end
%%
function [range_length] = SetRangeFull(obj)
%SetRangeFull Sets the range to full (we are interested in all samples).
try
obj.range_samples = audioread(obj.path);
catch
error('Problem with reading wav file. Exiting.')
end
obj.range_length = obj.total_samples;
range_length = obj.range_length;
end
%%
function [range_length] = SetRange(obj, start_sec, end_sec)
% SetRange Sets target range of interest.
%
%# [range_length] = SetRange(obj, start_sec, end_sec)
%# INPUT start_sec: staring point in target range
%# INPUT end_sec: ending point in target range
%# OUTPUT range_length: number of total samples available in the range
%
% To use full range call SetRangeFull().
% If start beyond end: throws exception.
% If end beyond end: sets end to end.
[start_sec, end_sec] = obj.checks( start_sec,end_sec );
% Full range if both zeroes:
%if(start_sec==0 && end_sec==0)
% start_sample = 1;
% stop_sample = obj.total_samples;
%else
start_sample = obj.seconds_to_samples(start_sec);
stop_sample = obj.seconds_to_samples(end_sec);
%end
obj.range_length = stop_sample - start_sample;
obj.range_samples = 0;
try
obj.range_samples = audioread(obj.path, [start_sample, stop_sample]);
catch
error('Problem with reading wav file. Exiting.')
end
range_length = obj.range_length;
end
%%
function [total_chunks] = SetChunkLength( obj, chunk_length )
% SetChunkLength Defines chunk length for chunk-by-chunk read.
%
%# [total_chunks] = SetChunkLength( obj, chunk_length )
%# INPUT chunk_length: desired chunk length
%# OUTPUT total_chunks: total number of available full chunks
%
% Abandonds last incomplete chunk.
obj.chunk_length = chunk_length;
obj.chunks_read = 0;
obj.total_chunks = round( obj.range_length / obj.chunk_length - 0.5 );
total_chunks = obj.total_chunks;
end
%%
function [total_chunks] = SetChunkLengthInMiliSeconds( obj, chunk_length_ms )
% SetChunkLengthInMiliSeconds Defines chunk length for chunk-by-chunk read.
%
%# [total_chunks] = SetChunkLengthInMiliSeconds( obj, chunk_length_ms )
%# INPUT chunk_length_ms: desired chunk length in mili-seconds
%# OUTPUT total_chunks: total number of available full chunks
%
% Abandonds last incomplete chunk.
seconds = chunk_length_ms/1000.0;
chunk_length_samples = seconds_to_samples( obj, seconds );
total_chunks = SetChunkLength( obj, chunk_length_samples );
end
%%
function [chunk, num_read] = ReadChunk( obj )
% ReadChunk Reads next chunk of blocklength.
%
%# [chunk, num_read] = ReadChunk( obj )
%# OUTPUT chunk: chunk samples
%# OUTPUT num_read: number of read samples.
%
% If next chunk incomplete: returns zero.
% If next chunk not available: returns zero.
start_pos = 1 + obj.chunks_read * obj.chunk_length;
stop_pos = start_pos + obj.chunk_length -1;
if( start_pos>obj.range_length || stop_pos>obj.range_length)
num_read = 0;
chunk = 0;
% warning('Reached the end of samples, nothing read.')
% To do: handle last incomplete frame.
return;
end
chunk = obj.range_samples(start_pos:stop_pos);
num_read = 1 + stop_pos - start_pos;
obj.chunks_read = 1 + obj.chunks_read;
end
%%
function progress = Progress(obj)
% Progress Returns progress in percentages.
progress = 100.0 * double(obj.chunks_read) / double(obj.total_chunks);
end
%%
function range = GetFullRange(obj)
% GetFullRange Returns all samples available.
range = obj.range_samples;
end
%%
function fs = GetSamplingRate(obj)
% GetSamplingRate Returns sampling rate.
fs = obj.fs;
end
%%
function samples = GetNumberOfSamples(obj)
samples = obj.total_samples;
end
%%
function num_chunks_read = GetNumberOfReadChunks(obj)
% GetNumberOfReadChunks Returns number of chunks read so far.
num_chunks_read = obj.chunks_read;
end
%%
function [samples, count] = GetSamples(obj, start_sec, end_sec)
% GetSamples Call to immediately get range of samples.
[start_sec, end_sec] = obj.checks( start_sec,end_sec );
start_sample = obj.seconds_to_samples(start_sec);
stop_sample = obj.seconds_to_samples(end_sec);
count = 1 + stop_sample - start_sample;
try
samples = audioread(obj.path, [start_sample, stop_sample]);
catch
error('Problem with reading wav file. Exiting.')
end
end
%%
function [samples, count] = GetAllSamples(obj)
% GetAllSamples Call to immediately get all of the samples.
try
samples = audioread(obj.path);
catch
error('Problem with reading wav file. Exiting.')
end
count = obj.total_samples;
end
end % methods public
methods (Access=private)
% Secs to samples
function [sample] = seconds_to_samples( obj, seconds )
sample = obj.fs * seconds;
end
% Check range
function [start_checked, end_checked] = checks(obj, start_sec, end_sec)
start_checked = start_sec;
end_checked = end_sec;
% Check fatal errors
if( start_sec>obj.total_seconds ||...
start_sec>=end_sec ||...
start_sec<0 ||...
end_sec<0 )
throw(MException( 'WavReader:FatalError', 'Range error.') );
end
% Handle overflow
if( end_sec > obj.total_seconds )
end_checked = obj.total_seconds;
end
end
end % methods private
end % class

Related

Why is my MATLAB code printing every value within the for loop?

I have code that breaks up a sound file into 1 sec chunks, calculates the RMS of the chunk, then plots all chunks. It works fine until I edited it to make it read through a folder rather than one user loaded file at at time. Now it prints every value of fs (all 32k) which obviously massively slows down the script. Here is the new script:
DirIn = 'D:\Trial'
eval(['filelist=dir(''' DirIn '/*.wav'')'])
for i = 1:length(filelist)
[y,fs] = audioread(strcat(DirIn,'/',filelist(i).name))
npts = length(y);
chunkDur = 1; % length of chunk to analyze in seconds
systemCal = 0; % this should be whatever dB corresponds to an amplitude of 1 in wav file
chunkPts = fs * chunkDur;
rms = [];
for i = 1:chunkPts:npts-chunkPts
chunkRMS = 20 * log10(std(y(i: i + chunkPts))) + systemCal; % rms of chunk in dB
rms = [rms; chunkRMS];
end
t = [0: length(rms) - 1] * chunkDur; % time scale
plot(t, rms)
xlabel('Time (s)');
ylabel('RMS dB');
end
For reference, here's the original that works:
npts = length(data);
chunkDur = 1; % length of chunk to analyze in seconds
systemCal = 0; % this should be whatever dB corresponds to an amplitude of 1 in wav file
chunkPts = fs * chunkDur;
rms = [];
for i = 1:chunkPts:npts-chunkPts
chunkRMS = 20 * log10(std(data(i: i + chunkPts))) + systemCal; % rms of chunk in dB
rms = [rms; chunkRMS];
end
t = [0: length(rms) - 1] * chunkDur; % time scale
plot(t, rms)
xlabel('Time (s)');
ylabel('RMS dB');
You missed a semicolon ; at the end of line [y,fs] = audioread(strcat(DirIn,'/',filelist(i).name)).
It signifies the end of a row and suppress an output of the code line. There is a nice blog-entry on this here.

Matlab - How can I write the values to an excel in a nested for loop

I have an Image which is 1944(R) x 2592 (C). I would like to take one column at a time; treating each column as an Image and calculate how many pixels among each row of that column contains value > half(max) value of that column. Those number of pixels are to be written to the excel sheet corresponding to it's respective column.
Image: the image
Here is what I have tried so far, I am not able to write it successfully.
clc;
sig = rgb2gray(imread('1.bmp')); % read in the image.
% imshow(sig);
ArraySize = size(sig); %1944(R) x 2592 (C)
[maxval, maxloc] = max(sig(:)); % Gives the max and the location
maxval; % max value
[maxloc_row, maxloc_col] = ind2sub(size(sig), maxloc); % convert logical
%-------------------------------------------------------------------%
% Count pixels through each column > half(max) value of that column
%-------------------------------------------------------------------%
newfilename = 'Results.csv'; % write new values to .csv files
Array = zeros(2592,2);
% % R = Array(:,1);
% y = Array(:,2);
for a = 1: 2592% maxloc_row = 635 maxloc_col = 1094
[a_maxval, a_maxloc] = max(sig(:,a)); % search max among every column.
% maxloc is the row at which maxval is.
newval = a_maxval/2; % averaged max value
% New structure for find width
x = 0;
x = Array(:, 1);
for b = 1: 1944 % maxloc_row = 635 maxloc_col = 1094
% R = b;
if sig(b,a) > newval
x=x+1;
end
end % End row search
x;
% y = x*(2.2); % pixels into microns
output = [num2cell(x)];
xlswrite(newfilename, output);
end % End column search
I think csvwrite can write data to csv file. Here's what you can try:
place output = []; somewhrere at top, says below clc;
then, replace
output = [num2cell(x)]; with output = [output x];
and
xlswrite(newfilename, output); with csvwrite(newfilename, output); but place it at the end of program because output has all x inside.
I have tried and it works.

Executing nested functions with a timer object

I am trying to write a program which acquires an image from a webcam, averages over several of the vertical pixel rows, displays the result and then applies a Gaussian fit to locate the peak position with a high degree of accuracy. All of this is to be done in real time. I used a timer object to run the function (called datain) which triggers the camera and acquires the data. To iterate and update the data the function includes a while loop. My code worked perfectly until I added a command inside the while loop to call another function (called GaussianFit) which preformed the fit. When this function is added I receive an error which says the callback function in the timer does not have enough inputs.
"Error while evaluating TimerFcn for timer 'timer-1' Not enough input arguments."
This seems odd since the data acquisition function provides all the inputs needed by the fitting function. My code is as follows:
function WaveAQ()
global webcamin
%%%%%%%%%%%%%%%%%%%%%%%
% Create video object %
%%%%%%%%%%%%%%%%%%%%%%%
dID = 2; vForm = 'MJPG_1280x720';
% Search for existing video objects to avoid creating multiple handles
vObj = imaqfind('DeviceID', dID, 'VideoFormat', vForm);
if isempty(vObj)
webcamin = videoinput('winvideo',dID,vForm);
else
webcamin = vObj{1};
end
% Configure # datasets to be averaged per measurement
set(webcamin,'FramesPerTrigger',1);
% Repeat until stopped
set(webcamin,'TriggerRepeat',Inf);
% Set to grayscale
set(webcamin,'ReturnedColorSpace','grayscale');
% Allow webcam to be triggered by timer
triggerconfig(webcamin,'manual')
% % View the properties for the selected video source object.
% src_obj = getselectedsource(webcamin);
% get(src_obj)
% Prompt for dark reading
j = 1;
j = input('Would you like to take a dark reading? (y/n): ','s');
switch j
case 'y'
j = 1;
case 'n'
j = 2;
end
if j == 1
prompt = input('Block input and enter any number to continue: ');
end
% We now define a function which will acquire data from the camera to be
% executed by the timer function
fig1 = figure(1);
function datain(~,event,input)
persistent image
h = 1; % Initialize Loop
bg = 0;
avgroi = 0;
% Calibration and fitting constants
tol = 1;
calib_slope = .003126;
calib_offset = 781.8;
spect = (1:1280)*calib_slope + calib_offset;
while h == 1
% Check if figure is open
h = ishandle(fig1);
trigger(input);
% First run finds dark reading
if j == 1
bg = getdata(input,1,'uint8');
j = 2;
else
image = getdata(input,1,'uint8');
image = image - bg; % Correct for background
npxy = length(image(:,1));
npxx = length(image(1,:));
% Region of interest for spectral data
dy_roi = 200;
y_roi = npxy/2;
% Region of interest for beam position
dx_roi = npxx/2;
x_roi = npxx/2;
avgroi = sum(image((y_roi-dy_roi):(y_roi+dy_roi),:))/(2*dy_roi);
avgroi = avgroi/256; % Normalize units
avg_y = (sum(image(:,(x_roi-dx_roi+1):(x_roi+dx_roi))).'/(2*dx_roi)).';
[cx,sx,Ipeak] = GaussianFit(avgroi,tol);
% cx = max(avgroi);
% sx = 2;
% Ipeak = max(avgroi);
subplot(2,1,1)
plot(spect,avgroi)
title('Spectrogram')
xlabel('Wavelength (nm)')
ylabel('Intensity (arb.)')
legend(['\lambda_P_e_a_k = ',num2str(cx),'nm'])
subplot(2,1,2)
plot(1:length(avg_y),avg_y/256)
title('Beam Profile in Y')
xlabel('Pixel #')
ylabel('Intensity (arb.)')
end
end
end
%%%%%%%%%%%%%%%%%%%
% Define timer object to execute daq %
%%%%%%%%%%%%%%%%%%%
% Set callback properies
timerfcn = #datain;
% Image acquisition rate
Raq = 5;
timer_exec = timer('TimerFcn',{timerfcn,webcamin},'period',1/Raq,'BusyMode','drop');% Maybe change busy mode to queue if regular acquisition interval needed.
% timer_exec2 = timer('TimerFcn',#GaussianFit,'period',1/Raq,'BusyMode','drop');
% Execute acquistion
start(webcamin);
preview(webcamin);
start(timer_exec);
% start(timer_exec2);
% Clean system
stop(timer_exec);
% stop(timer_exec2);
delete(timer);
stop(webcamin);
delete(webcamin);
clear functions;
end
Can anyone tell me why the timer needs more inputs when GaussianFit is called inside the loop?

How does the choice of the wavelet function impact the speed of cwt()?

In cwt() I can specify which wavelet function to use. How does that impact the speed of cwt()?
Here is a benchmark, which I run with the -singleCompThread option when starting MATLAB to force it to use a single computational thread. cwt() was passed a 1,000,000-sample signal and asked to compute scales 1 to 10. My CPU is an i7-3610QM.
Code used:
clear all
%% Benchmark parameters
results_file_name = 'results_scale1-10.csv';
number_of_random_runs = 10;
scales = 1:10;
number_of_random_samples = 1000000;
%% Construct a cell array containing all the wavelet names
wavelet_haar_names = {'haar'};
wavelet_db_names = {'db1'; 'db2'; 'db3'; 'db4'; 'db5'; 'db6'; 'db7'; 'db8'; 'db9'; 'db10'};
wavelet_sym_names = {'sym2'; 'sym3'; 'sym4'; 'sym5'; 'sym6'; 'sym7'; 'sym8'};
wavelet_coif_names = {'coif1'; 'coif2'; 'coif3'; 'coif4'; 'coif5'};
wavelet_bior_names = {'bior1.1'; 'bior1.3'; 'bior1.5'; 'bior2.2'; 'bior2.4'; 'bior2.6'; 'bior2.8'; 'bior3.1'; 'bior3.3'; 'bior3.5'; 'bior3.7'; 'bior3.9'; 'bior4.4'; 'bior5.5'; 'bior6.8'};
wavelet_rbior_names = {'rbio1.1'; 'rbio1.3'; 'rbio1.5'; 'rbio2.2'; 'rbio2.4'; 'rbio2.6'; 'rbio2.8'; 'rbio3.1'; 'rbio3.3'; 'rbio3.5'; 'rbio3.7'; 'rbio3.9'; 'rbio4.4'; 'rbio5.5'; 'rbio6.8'};
wavelet_meyer_names = {'meyr'};
wavelet_dmeyer_names = {'dmey'};
wavelet_gaus_names = {'gaus1'; 'gaus2'; 'gaus3'; 'gaus4'; 'gaus5'; 'gaus6'; 'gaus7'; 'gaus8'};
wavelet_mexh_names = {'mexh'};
wavelet_morl_names = {'morl'};
wavelet_cgau_names = {'cgau1'; 'cgau2'; 'cgau3'; 'cgau4'; 'cgau5'};
wavelet_shan_names = {'shan1-1.5'; 'shan1-1'; 'shan1-0.5'; 'shan1-0.1'; 'shan2-3'};
wavelet_fbsp_names = {'fbsp1-1-1.5'; 'fbsp1-1-1'; 'fbsp1-1-0.5'; 'fbsp2-1-1'; 'fbsp2-1-0.5'; 'fbsp2-1-0.1'};
wavelet_cmor_names = {'cmor1-1.5'; 'cmor1-1'; 'cmor1-0.5'; 'cmor1-1'; 'cmor1-0.5'; 'cmor1-0.1'};
% Concatenate all wavelet names into a single cell array
wavelet_categories_names = who('wavelet*names');
wavelet_names = {};
for wavelet_categories_number=1:size(wavelet_categories_names,1)
temp = wavelet_categories_names(wavelet_categories_number);
temp = eval(temp{1});
wavelet_names = vertcat(wavelet_names, temp);
end
%% Prepare data
random_signal = rand(number_of_random_runs,number_of_random_samples);
%% Run benchmarks
result_file_ID = fopen(results_file_name, 'w');
for wavelet_number = 1:size(wavelet_names,1)
wavelet_name = wavelet_names(wavelet_number,:)
% Compute wavelet on a random signal
tic
for run = 1:number_of_random_runs
cwt(random_signal(run, :),scales,wavelet_name{1});
end
run_time_random_test = toc
fprintf(result_file_ID, '%s,', wavelet_name{1})
fprintf(result_file_ID, '%d\n', run_time_random_test)
end
size(wavelet_names,1)
fclose(result_file_ID);
If you want to see the impact of the choice of the scale:
Code used:
clear all
%% Benchmark parameters
results_file_name = 'results_sym2_change_scale.csv';
number_of_random_runs = 10;
scales = 1:10;
number_of_random_samples = 10000000;
% wavelet_names = {'sym2', 'sym3'}%, 'sym4'};
output_directory = 'output';
wavelet_names = get_all_wavelet_names();
%% Prepare data
random_signal = rand(number_of_random_runs,number_of_random_samples);
%% Prepare result folder
if ~exist(output_directory, 'dir')
mkdir(output_directory);
end
%% Run benchmarks
result_file_ID = fopen(results_file_name, 'w');
for wavelet_number = 1:size(wavelet_names,1)
wavelet_name = wavelet_names{wavelet_number}
if wavelet_number > 1
fprintf(result_file_ID, '%s\n', '');
end
fprintf(result_file_ID, '%s', wavelet_name)
run_time_random_test_scales = zeros(size(scales,2),1);
for scale_number = 1:size(scales,2)
scale = scales(scale_number);
% Compute wavelet on a random signal
tic
for run = 1:number_of_random_runs
cwt(random_signal(run, :),scale,wavelet_name);
end
run_time_random_test = toc
fprintf(result_file_ID, ',%d', run_time_random_test)
run_time_random_test_scales(scale_number) = run_time_random_test;
end
figure
bar(run_time_random_test_scales)
title(['Run time on random signal for ' wavelet_name])
xlabel('Scale')
ylabel('Run time (seconds)')
save_figure( fullfile(output_directory, ['run_time_random_test_' wavelet_name]) )
close all
end
size(wavelet_names,1)
fclose(result_file_ID);
With 3 functions:
get_all_wavelet_names.m:
function [ wavelet_names ] = get_all_wavelet_names( )
%GET_ALL_WAVELET_NAMES Get a list of available wavelet functions
%% Construct a cell array containing all the wavelet names
wavelet_haar_names = {'haar'};
wavelet_db_names = {'db1'; 'db2'; 'db3'; 'db4'; 'db5'; 'db6'; 'db7'; 'db8'; 'db9'; 'db10'};
wavelet_sym_names = {'sym2'; 'sym3'; 'sym4'; 'sym5'; 'sym6'; 'sym7'; 'sym8'};
wavelet_coif_names = {'coif1'; 'coif2'; 'coif3'; 'coif4'; 'coif5'};
wavelet_bior_names = {'bior1.1'; 'bior1.3'; 'bior1.5'; 'bior2.2'; 'bior2.4'; 'bior2.6'; 'bior2.8'; 'bior3.1'; 'bior3.3'; 'bior3.5'; 'bior3.7'; 'bior3.9'; 'bior4.4'; 'bior5.5'; 'bior6.8'};
wavelet_rbior_names = {'rbio1.1'; 'rbio1.3'; 'rbio1.5'; 'rbio2.2'; 'rbio2.4'; 'rbio2.6'; 'rbio2.8'; 'rbio3.1'; 'rbio3.3'; 'rbio3.5'; 'rbio3.7'; 'rbio3.9'; 'rbio4.4'; 'rbio5.5'; 'rbio6.8'};
wavelet_meyer_names = {'meyr'};
wavelet_dmeyer_names = {'dmey'};
wavelet_gaus_names = {'gaus1'; 'gaus2'; 'gaus3'; 'gaus4'; 'gaus5'; 'gaus6'; 'gaus7'; 'gaus8'};
wavelet_mexh_names = {'mexh'};
wavelet_morl_names = {'morl'};
wavelet_cgau_names = {'cgau1'; 'cgau2'; 'cgau3'; 'cgau4'; 'cgau5'};
wavelet_shan_names = {'shan1-1.5'; 'shan1-1'; 'shan1-0.5'; 'shan1-0.1'; 'shan2-3'};
wavelet_fbsp_names = {'fbsp1-1-1.5'; 'fbsp1-1-1'; 'fbsp1-1-0.5'; 'fbsp2-1-1'; 'fbsp2-1-0.5'; 'fbsp2-1-0.1'};
wavelet_cmor_names = {'cmor1-1.5'; 'cmor1-1'; 'cmor1-0.5'; 'cmor1-1'; 'cmor1-0.5'; 'cmor1-0.1'};
% Concatenate all wavelet names into a single cell array
wavelet_categories_names = who('wavelet*names');
wavelet_names = {};
for wavelet_categories_number=1:size(wavelet_categories_names,1)
temp = wavelet_categories_names(wavelet_categories_number);
temp = eval(temp{1});
wavelet_names = vertcat(wavelet_names, temp);
end
end
save_figure.m:
function [ ] = save_figure( output_graph_filename )
% Record aa figure as PNG and fig files
% Create the folder if it doesn't exist already.
[pathstr, name, ext] = fileparts(output_graph_filename);
if ~exist(pathstr, 'dir')
mkdir(pathstr);
end
h = gcf;
set(0,'defaultAxesFontSize',18) % http://www.mathworks.com/support/solutions/en/data/1-8XOW94/index.html?solution=1-8XOW94
boldify(h);
print('-dpng','-r600', [output_graph_filename '.png']);
print(h,[output_graph_filename '.pdf'],'-dpdf','-r600')
saveas(gcf,[output_graph_filename '.fig'], 'fig')
end
and boldify.m:
function boldify(h,g)
%BOLDIFY Make lines and text bold for standard viewgraph style.
% BOLDIFY boldifies the lines and text of the current figure.
% BOLDIFY(H) applies to the graphics handle H.
%
% BOLDIFY(X,Y) specifies an X by Y inch graph of the current
% figure. If text labels have their 'UserData' data property
% set to 'slope = ...', then the 'Rotation' property is set to
% account for changes in the graph's aspect ratio. The
% default is MATLAB's default.
% S. T. Smith
% The name of this function does not represent an endorsement by the author
% of the egregious grammatical trend of verbing nouns.
if nargin < 1, h = gcf;, end
% Set (and get) the default MATLAB paper size and position
set(gcf,'PaperPosition','default');
units = get(gcf,'PaperUnits');
set(gcf,'PaperUnits','inches');
fsize = get(gcf,'PaperPosition');
fsize = fsize(3:4); % Figure size (X" x Y") on paper.
psize = get(gcf,'PaperSize');
if nargin == 2 % User specified graph size
fsize = [h,g];
h = gcf;
end
% Set the paper position of the current figure
set(gcf,'PaperPosition', ...
[(psize(1)-fsize(1))/2 (psize(2)-fsize(2))/2 fsize(1) fsize(2)]);
fsize = get(gcf,'PaperPosition');
fsize = fsize(3:4); % Graph size (X" x Y") on paper.
set(gcf,'PaperUnits',units); % Back to original
% Get the normalized axis position of the current axes
units = get(gca,'Units');
set(gca,'Units','normalized');
asize = get(gca,'Position');
asize = asize(3:4);
set(gca,'Units',units);
ha = get(h,'Children');
for i=1:length(ha)
% if get(ha(i),'Type') == 'axes'
% changed by B. A. Miller
if strcmp(get(ha(i), 'Type'), 'axes') == 1
units = get(ha(i),'Units');
set(ha(i),'Units','normalized');
asize = get(ha(i),'Position'); % Axes Position (normalized)
asize = asize(3:4);
set(ha(i),'Units',units);
[m,j] = max(asize); j = j(1);
scale = 1/(asize(j)*fsize(j)); % scale*inches -normalized units
set(ha(i),'FontWeight','Bold');
set(ha(i),'LineWidth',2);
[m,k] = min(asize); k = k(1);
if asize(k)*fsize(k) > 1/2
set(ha(i),'TickLength',[1/8 1.5*1/8]*scale); % Gives 1/8" ticks
else
set(ha(i),'TickLength',[3/32 1.5*3/32]*scale); % Gives 3/32" ticks
end
set(get(ha(i),'XLabel'),'FontSize',18); % 14-pt labels
set(get(ha(i),'XLabel'),'FontWeight','Bold');
set(get(ha(i),'XLabel'),'VerticalAlignment','top');
set(get(ha(i),'YLabel'),'FontSize',18); % 14-pt labels
set(get(ha(i),'YLabel'),'FontWeight','Bold');
%set(get(ha(i),'YLabel'),'VerticalAlignment','baseline');
set(get(ha(i),'Title'),'FontSize',18); % 16-pt titles
set(get(ha(i),'Title'),'FontWeight','Bold');
% set(get(ha(i), 'FontSize',20, 'XTick',[]));
end
hc = get(ha(i),'Children');
for j=1:length(hc)
chtype = get(hc(j),'Type');
if chtype(1:4) == 'text'
set(hc(j),'FontSize',17); % 12 pt descriptive labels
set(hc(j),'FontWeight','Bold');
ud = get(hc(j),'UserData'); % User data
if length(ud) 8
if ud(1:8) == 'slope = ' % Account for change in actual slope
slope = sscanf(ud,'slope = %g');
slope = slope*(fsize(2)/fsize(1))/(asize(2)/asize(1));
set(hc(j),'Rotation',atan(slope)/pi*180);
end
end
elseif chtype(1:4) == 'line'
set(hc(j),'LineWidth',2);
end
end
end
Bonus: correlation between all wavelets on a random signal with 1000000 samples with the first 10 scales:
Code used:
%% PRE-REQUISITE: You need to download http://www.mathworks.com/matlabcentral/fileexchange/24253-customizable-heat-maps , which gives the function heatmap()
%% Benchmark parameters
scales = 1:10;
number_of_random_samples = 1000000;
% wavelet_names = {'sym2'; 'sym3'; 'sym4'; 'sym5'; 'sym6'; 'sym7'; 'sym8'};
% wavelet_names = {'cgau1'; 'cgau2'; 'cgau3'; 'cgau4'; 'cgau5'};
wavelet_names = {'db2'; 'sym2'};
OUTPUT_FOLDER = 'output_corr';
% wavelet_names = get_all_wavelet_names(); % WARNING: you need to remove all complex wavelets, viz. cgau1, shan, fbsp and cmor, and the heatmap will be pissed to see complex values coming to her.
%% Prepare data
random_signal = rand(1,number_of_random_samples);
results = zeros(size(wavelet_names,1), number_of_random_samples);
%% Prepare result folder
if ~exist(OUTPUT_FOLDER, 'dir')
mkdir(OUTPUT_FOLDER);
end
%% Run benchmarks
for scale_number = 1:size(scales,2)
scale = scales(scale_number);
for wavelet_number = 1:size(wavelet_names,1)
wavelet_name = wavelet_names{wavelet_number}
% Compute wavelet on a random signal
run = 1;
results(wavelet_number, :) = cwt(random_signal(run, :),scale,wavelet_name);
if wavelet_number == 999
break
end
end
correlation_results = corrcoef(results')
heatmap(correlation_results, [], [], '%0.2f', 'MinColorValue', -1.0, 'MaxColorValue', 1.0, 'Colormap', 'jet',...
'Colorbar', true, 'ColorLevels', 64, 'UseFigureColormap', false);
title(['Correlation matrix for scale ' num2str(scale)]);
xlabel(['Wavelet 1 to ' num2str(size(wavelet_names,1)) ' for scale ' num2str(scale)]);
ylabel(['Wavelet 1 to ' num2str(size(wavelet_names,1)) ' for scale ' num2str(scale)]);
snapnow
print('-dpng','-r600',fullfile(OUTPUT_FOLDER, ['scalecorr' num2str(scale) '.png']))
end
Correlation for each wavelet between different scales (1 to 100):
Code used:
%% PRE-REQUISITE: You need to download http://www.mathworks.com/matlabcentral/fileexchange/24253-customizable-heat-maps , which gives the function heatmap()
%% Benchmark parameters
scales = 1:100;
number_of_random_samples = 1000000;
% wavelet_name = 'gaus2';
% wavelet_names = {'sym2', 'sym3'}%, 'sym4'};
OUTPUT_FOLDER = 'output_corr';
wavelet_names = get_all_wavelet_names(); % WARNING: you need to remove all complex wavelets, viz. cgau1, shan, fbsp and cmor, and the heatmap will be pissed to see complex values coming to her.
%% Prepare data
random_signal = rand(1,number_of_random_samples);
results = zeros(size(scales,2), number_of_random_samples);
%% Prepare result folder
if ~exist(OUTPUT_FOLDER, 'dir')
mkdir(OUTPUT_FOLDER);
end
%% Run benchmarks
for wavelet_number = 1:size(wavelet_names,1)
wavelet_name = wavelet_names{wavelet_number}
run_time_random_test_scales = zeros(size(scales,2),1);
for scale_number = 1:size(scales,2)
scale = scales(scale_number);
run = 1;
% Compute wavelet on a random signal
results(scale_number, :) = cwt(random_signal(run, :),scale,wavelet_name);
end
correlation_results = corrcoef(results')
heatmap(correlation_results, [], [], '%0.2f', 'MinColorValue', -1.0, 'MaxColorValue', 1.0, 'Colormap', 'jet',...
'Colorbar', true, 'ColorLevels', 64, 'UseFigureColormap', false);
title(['Correlation matrix for wavelet ' wavelet_name]);
xlabel(['Scales 1 to ' num2str(max(scales)) ' for wavelet ' wavelet_name]);
ylabel(['Scales 1 to ' num2str(max(scales)) ' for wavelet ' wavelet_name]);
snapnow
print('-dpng','-r600',fullfile(OUTPUT_FOLDER, [wavelet_name '_scalecorr_scale1to' num2str(max(scales)) '.png']))
end

Matlab Computation Time for Synonyms

I am importing wordnet library in matlab code given below but it takes almost 5-10 seconds for giving me synonyms of each word.
can its time be reduced in some way because I have to test it on numerous words
Thanks
Code:
function [status,varargout] = dictionary(text)
%DICTIONARY checks the spelling status of word(s) and returns synonyms if found.
%
% [status,synonyms] = dictionary(text);
% status = dictionary(text);
%
% text: word(s) separated by a single space.
% status: returns '1' if word(s) exist in dictionary or '0' otherwise.
% synonyms: an array of synonyms of word(s) or otherwise returns
% a message 'No Synonyms Found!' or 'Incorrect Spelling!'.
%
% Examples:
% [status,synonyms] = dictionary('peddler');
% [status,synonyms] = dictionary('walk match ground');
% status = dictionary('hysteria');
%
% Separating string of words into arrays of words.
k=1;
temp='';
% t=fopen('Crime.txt');
% text=textscan(t,'%s');
% text=texts{1,1};
% fclose(t);
%text='ignorevbnnn';
for n=1:length(text);
if ~isspace(text(n))
temp = [temp text(n)];
else
if ~isspace(text(n-1))
words{k} = temp;
end
temp='';
k=k+1;
end
end
words{k} = temp;
% Opening MS Word and Starting the Spelling Check & Finding Synonyms
Doc = actxserver('Word.Application');
m=1;
for n=1:length(words)
if ~isempty(words{n})
status(m) = invoke(Doc,'CheckSpelling',words{n},[],1,1);
if nargout==2
X = invoke(Doc,'SynonymInfo',words{n});
Synonyms = get(X,'MeaningList');
Meanings{m,1} = words{n};
if length(Synonyms)==0 & status(m)==1
Meanings{m,2} = 'No Synonyms Found!';
elseif status(m)==0
Meanings{m,2} = 'Incorrect Spelling!';
else
for k=2:length(Synonyms)+1
Meanings{m,k} = Synonyms{k-1};
end
end
end
m=m+1;
end
end
if exist('Meanings','var')
varargout = {Meanings};
end
status = all(status);
invoke(Doc,'Quit');
delete(Doc);