Large Data Array manipulations in MATLAB - arrays

I have a large data set in an array <1x43 cell>. The data size is really large, these are some of the cell dimensions - 5 are <1x327680 double>, 11 are <1x1376256 double>
I am attempting to carry out a resample operation which I have a function for. (Function code shown below). I am trying to take an entire cell from the array, perform the Resample operation and store the result back in the same array location or a different one.
However, I get the following error in line 19 or the Resample function -
"Error using zeros
Maximum variable size allowed by the program is exceeded.
Error in Resample (line 19)
obj = zeros(t,1);
I run into an out of memory error when I comment our that line 19.
Please is there a more efficient way to manipulate such large data sets?
Thank you.
Actual Code:
%% To load each ".dat" file for the 51 attributes to an array.
a = dir('*.dat');
for i = 1:length(a)
eval(['load ' a(i).name ' -ascii']);
end
attributes = length(a);
% Scan folder for number of ".dat" files
datfiles = dir('*.dat');
% Count Number of ".dat" files
numfiles = length(datfiles);
% Read files in to MATLAB
for i = 1:1:numfiles
A{i} = csvread(datfiles(i).name);
end
% Remove discarded variables
ind = [1 22 23 24 25 26 27 32]; % Variables to be removed.
A(ind) = [];
% Reshape all the data into columns - (n x 1)
for i = 1:1:length(A)
temp = A{1,i};
[x,y] = size(temp);
if x == 1 && y ~= 1
temp = temp';
A{1,i} = temp;
end
end
% Retrieves the frequency data for the attributes from Excel spreadsheet
frequency = xlsread('C:\Users\aajwgc\Documents\MATLAB\Research Work\Data\testBig\frequency');
% Removing recorded frequency for discarded variables
frequency(ind) = [];
% Upsampling all the attributes to desired frequency
prompt = {'Frequency (Hz):'};
dlg_title = 'Enter desired output frequency for all attributes';
num_lines = 1;
def = {'50'};
answer= inputdlg(prompt,dlg_title,num_lines,def);
OutFreq = str2num(answer{1});
m = 1;
n = length(frequency);
A_resampled = cell(m,n);
A_resampled(:) = {''};
for i = length(frequency);
raw = cell2mat(A(1,i));
temp= Resample(raw, frequency(i,:), OutFreq);
A_resampled{i} = temp(i);
end
Resample Function:
function obj = Resample(InputData, InFreq, OutFreq, varargin)
%% Preliminary setup
% Allow for selective down-sizing by specifying type
type = 'mean'; %default to the mean/average
if size(varargin,2) > 0
type = varargin{1};
end
% Determine the necessary resampling factor
factor = OutFreq / InFreq;
%% No refactoring required
if (factor == 1)
obj = InputData;
%% Up-Sampling required
elseif (factor > 1)
t = factor * numel(InputData(1:end));
**obj = zeros(t,1); ----------------> Line 19 where I get the error message.**
for i = 1:factor:t
y = ((i-1) / factor) + 1;
z = InputData(y);
obj(i:i+factor) = z;
end
%% Down-Sampling required
elseif (factor < 1)
t = numel(InputData(1:end));
t = floor(t * factor);
obj = zeros(t,1);
factor = int32(1/factor);
if strcmp(type,'mean') %default is mean (process first)
for i = 1:t
y = (factor * (i-1)) + 1;
obj(i) = mean(InputData(y:y+factor-1));
end
elseif strcmp(type,'min')
for i = 1:t
y = (factor * (i-1)) + 1;
obj(i) = min(InputData(y:y+factor-1));
end
elseif strcmp(type,'max')
for i = 1:t
y = (factor * (i-1)) + 1;
obj(i) = max(InputData(y:y+factor-1));
end
elseif strcmp(type,'mode')
for i = 1:t
y = (factor * (i-1)) + 1;
obj(i) = mode(InputData(y:y+factor-1));
end
elseif strcmp(type,'sum')
for i = 1:t
y = (factor * (i-1)) + 1;
obj(i) = sum(InputData(y:y+factor-1));
end
elseif strcmp(type,'single')
for i = 1:t
y = (factor * (i-1)) + 1;
obj(i) = InputData(y);
end
else
obj = NaN;
end
else
obj = NaN;
end

If you have the DSP System Toolbox, you could use, e.g., the dsp.FIRInterpolator System Object (http://www.mathworks.co.uk/help/dsp/ref/dsp.firinterpolatorclass.html ) and call its step() function repeatedly to avoid processing all the data in one go.
By the way, up/downsampling (interpolation and decimation) are more complex concepts than you have assumed; in the most general sense they both require some form of filtering to remove artifacts that such processes generate.
You could design these filters yourself and convolve your signal with them, but doing this filter design requires a solid foundation in signal processing. If you want to go this route, I suggest picking up a textbook from somewhere as easy to get wrong without a reference text.

Related

Large substitution from symbolic matrix to numerical values while keeping 4 unknowns into the new matrix

I have to solve the equality between 2 matrices 12x12 containing a lot of symbolic variables and with which I perform inversion of the matrix. There are only one unknown called SIGAM_O, and FISH_O_SYM(1,1), FISH_O_SYM(1,2) and FISH_O_SYM(2,2) (FISH_O_SYM(2,1) = FISH_O_SYM(1,2).
My system is solved fastly when I take for example 2 matrices 2x2, the inversion is pretty direct.
Now, with the case of 2 matrices 12x12, I need before actually to inverse a 31x31 matrix of symbolic variables (I marginalize after), since inversion takes a lot of time.
I would like to benefit from my GPU NVIDIA card to achieve this inversion faster but the GPU optimization is not supported currently for Symbolic arrays.
Below the script where you will find the line of inversion:
COV_ALL = inv(FISH_SYM)
and the entire code:
clear;
clc;
format long;
% 2 Fisher Matrixes symbolic : FISH_GCsp_SYM, : 1 cosmo params + 1 bias spectro put for common
% FISH_XC_SYM : 1 cosmo params + 2 bias photo correlated
% GCsp Fisher : 7 param cosmo and 5 bias spectro which will be summed
FISH_GCsp_SYM = sym('sp_', [17,17], 'positive');
% Force symmetry for GCsp
FISH_GCsp_SYM = tril(FISH_GCsp_SYM.') + triu(FISH_GCsp_SYM,1)
% GCph Fisher : 7 param cosmo + 3 I.A + 11 bias photo correlated
FISH_XC_SYM = sym('xc_', [21,21], 'positive');
% Force symmetry for GCph
FISH_XC_SYM = tril(FISH_XC_SYM.') + triu(FISH_XC_SYM,1)
% Brutal Common Bias : sum of 7 cosmo param ans 5 bias spectro : FISH_ALL1 = first left matrix
FISH_ALL1 = sym('xc_', [12,12], 'positive');
% Sum cosmo
FISH_ALL1(1:7,1:7) = FISH_GCsp_SYM(1:7,1:7) + FISH_XC_SYM(1:7,1:7);
% Brutal sum of bias
FISH_ALL1(7:12,7:12) = FISH_GCsp_SYM(7:12,7:12) + FISH_XC_SYM(15:20,15:20);
% Adding new observable "O" terms
FISH_O_SYM = sym('o_', [2,2], 'positive');
% Definition of sigma_o
SIGMA_O = sym('sigma_o', 'positive');
FISH_O_SYM = 1/(SIGMA_O*SIGMA_O) * FISH_O_SYM
% Force symmetry
FISH_O_SYM = (tril(FISH_O_SYM.') + triu(FISH_O_SYM,1))
FISH_O_SYM
%FISH_SYM = sym('xc_', [31,31], 'positive');
%FISH_BIG_GCsp = sym('sp_', [31,31], 'positive');
%FISH_BIG_XC = sym('xc_', [31,31], 'positive');
FISH_SYM = zeros(31,31,'sym');
FISH_BIG_GCsp = zeros(31,31,'sym');
FISH_BIG_XC = zeros(31,31,'sym');
% Block bias spectro + pshot and correlations;
FISH_BIG_GCsp(1:7,1:7) = FISH_GCsp_SYM(1:7,1:7);
FISH_BIG_GCsp(7:17,7:17) = FISH_GCsp_SYM(7:17,7:17);
FISH_BIG_GCsp(1:7,7:17) = FISH_GCsp_SYM(1:7,7:17);
FISH_BIG_GCsp(7:17,1:7) = FISH_GCsp_SYM(7:17,1:7);
% Block bias photo and correlations;
FISH_BIG_XC(1:7,1:7) = FISH_XC_SYM(1:7,1:7);
FISH_BIG_XC(21:31,21:31) = FISH_XC_SYM(11:21,11:21);
FISH_BIG_XC(1:7,21:31) = FISH_XC_SYM(1:7,11:21);
FISH_BIG_XC(21:31,1:7) = FISH_XC_SYM(11:21,1:7);
% Block I.A and correlations;
FISH_BIG_XC(18:20,18:20) = FISH_XC_SYM(8:10,8:10);
FISH_BIG_XC(1:7,18:20) = FISH_XC_SYM(1:7,8:10);
FISH_BIG_XC(18:20,1:7) = FISH_XC_SYM(8:10,1:7);
% Final summation
FISH_SYM = FISH_BIG_GCsp + FISH_BIG_XC;
% Add O observable
FISH_SYM(6,6) = FISH_SYM(6,6) + FISH_O_SYM(1,1);
FISH_SYM(6,26) = FISH_SYM(6,26) + FISH_O_SYM(2,2);
FISH_SYM(26,6) = FISH_SYM(26,6) + FISH_O_SYM(1,2);
FISH_SYM(26,26) = FISH_SYM(26,26) + FISH_O_SYM(2,1);
% Force symmetry
FISH_SYM = (tril(FISH_SYM.') + triu(FISH_SYM,1))
% Marginalize FISH_SYM2 in order to get back a 2x2 matrix
% Invert to marginalyze : take a long long time
COV_ALL = inv(FISH_SYM);
% Marginalize
COV_ALL([13:31],:) = [];
COV_ALL(:,[13:31]) = [];
FISH_ALL2 = inv(COV_ALL);
FISH_ALL1
FISH_ALL2
% Matricial equation to solve
eqn = FISH_ALL1 == FISH_ALL2;
% Solving : sigma_o unknown
[solx, parameters, conditions] = solve(eqn, SIGMA_O, 'ReturnConditions', true);
solx
Actually, this inversion of 31x31 size takes a long long time (I had to stop it).
So, now, the strategy is to replace almost all the symbolic unknowns by numerical values: I want just to keep 4 unknown (SIGAM_O, and FISH_O_SYM(1,1), FISH_O_SYM(1,2) and FISH_O_SYM(2,2) (FISH_O_SYM(2,1) = FISH_O_SYM(1,2))
So, I would like to know how to do a large substitution of arrays FISH_XC_SYM and FISH_GCsp_SYM by numerical values of the equivalent of these 2 matrixes.
I can do for example:
FISG_GCsp_NUM = load('Fisher_GCsp_num.dat')
FISG_XC_NUM = load('Fisher_XC_num.dat')
But how to assign quickly to both arrays FISH_GCsp_SYM and FISH_XC_SYM the numerical values of arrays FISH_GCsp_NUM and FISH_XC_NUM, all of this while keeping the 4 unknown above?
(Posted answer on behalf of the question author in order to move it to the answer space).
I resolve this issue by doing simply:
FISH_GCsp_SYM = load('file1.dat);
FISH_XC_SYM = load('file2.dat');
FISH_SYM = zeros(31,31,'sym');
FISH_BIG_GCsp = zeros(31,31,'sym');
FISH_BIG_XC = zeros(31,31,'sym');
% Block bias spectro + pshot and correlations;
FISH_BIG_GCsp(1:7,1:7) = FISH_GCsp_SYM(1:7,1:7);
FISH_BIG_GCsp(7:17,7:17) = FISH_GCsp_SYM(7:17,7:17);
FISH_BIG_GCsp(1:7,7:17) = FISH_GCsp_SYM(1:7,7:17);
FISH_BIG_GCsp(7:17,1:7) = FISH_GCsp_SYM(7:17,1:7);
% Block bias photo and correlations;
FISH_BIG_XC(1:7,1:7) = FISH_XC_SYM(1:7,1:7);
FISH_BIG_XC(21:31,21:31) = FISH_XC_SYM(11:21,11:21);
FISH_BIG_XC(1:7,21:31) = FISH_XC_SYM(1:7,11:21);
FISH_BIG_XC(21:31,1:7) = FISH_XC_SYM(11:21,1:7);
% Block I.A and correlations;
FISH_BIG_XC(18:20,18:20) = FISH_XC_SYM(8:10,8:10);
FISH_BIG_XC(1:7,18:20) = FISH_XC_SYM(1:7,8:10);
FISH_BIG_XC(18:20,1:7) = FISH_XC_SYM(8:10,1:7);
and everything is done!

Logical indexing in matlab - need help to make faster

This is what I am trying to do, created a random array to demonstrate:
% all IDs
all_IDS = 1:216000000;
% Array 1
X = round(1550*rand(216000000,1));
Y = round(1550*rand(216000000,1));
Z = round(90*rand(216000000,1));
% Array 2
Xsub = round(1550*rand(160000,1));
Ysub = round(1550*rand(160000,1));
Zsub = round(90*rand(160000,1));
del_val =1;
% required o/p
reqd_op = zeros(1,10);
% boolean indexing
indx =1;
for jj = 1:160000
VID_X = Xsub(jj);
VID_Y = Ysub(jj);
VID_Z = Zsub(jj);
I2 = (X>VID_X-del_val & X<VID_X+del_val)& (Y>VID_Y-del_val & Y<VID_Y+del_val) & (Z>VID_Z-del_val & Z<VID_Z+del_val);
len = numel(all_IDS(I2));
reqd_op(1,indx:indx+len-1) = all_IDS(I2);
indx=indx+len;
end
The above code takes a lot of time as I am dealing with a very large array , Is there a way to eliminate the for loop, meaning, instead of doing Boolean indexing element by element - can I do it for the whole array at once ?
This will run x2.5 faster, anyway, array is too big so it still takes 0.3s per loop, so 160000 loops is like 13 hours on single cpu.
if ~exist('X','var')
% Array 1
X = round(1550*rand(216000000,1,'single'));
Y = round(1550*rand(216000000,1,'single'));
Z = round(90*rand(216000000,1,'single'));
% Array 2
Xsub = round(1550*rand(160000,1,'single'));
Ysub = round(1550*rand(160000,1,'single'));
Zsub = round(90*rand(160000,1,'single'));
end
del_val =single(1);
reqd_op = zeros(1,10,'single');% required o/p
tic
index =1;
for jj = 1:10
VID_X = Xsub(jj);
VID_Y = Ysub(jj);
VID_Z = Zsub(jj);
IdxFinal=[];
Idx1=find(abs(X-VID_X)<del_val); %little better than X>VID_X-del_val & X<VID_X+del_val)
if ~isempty(Idx1)
Idx2 = Idx1(Y(Idx1)>VID_Y-del_val & Y(Idx1)<VID_Y+del_val);
if ~isempty(Idx2)
Idx3= Idx2(Z(Idx2)>VID_Z-del_val & Z(Idx2)<VID_Z+del_val);
IdxFinal=Idx3;
end
end
len = length(IdxFinal);
index=index+len;
if len>0
reqd_op(1,index:index+len-1) = IdxFinal;
end
end
toc

Array not defined

I'm still confused why am not able to know the results of this small algorithm of my array. the array has almost 1000 number 1-D. am trying to find the peak and the index of each peak. I did found the peaks, but I can't find the index of them. Could you please help me out. I want to plot all my values regardless the indexes.
%clear all
%close all
%clc
%// not generally appreciated
%-----------------------------------
%message1.txt.
%-----------------------------------
% t=linspace(0,tmax,length(x)); %get all numbers
% t1_n=0:0.05:tmax;
x=load('ww.txt');
tmax= length(x) ;
tt= 0:tmax -1;
x4 = x(1:5:end);
t1_n = 1:5:tt;
x1_n_ref=0;
k=0;
for i=1:length(x4)
if x4(i)>170
if x1_n_ref-x4(i)<0
x1_n_ref=x4(i);
alpha=1;
elseif alpha==1 && x1_n_ref-x4(i)>0
k=k+1;
peak(k)=x1_n_ref; // This is my peak value. but I also want to know the index of it. which will represent the time.
%peak_time(k) = t1_n(i); // this is my issue.
alpha=2;
end
else
x1_n_ref=0;
end
end
%----------------------
figure(1)
% plot(t,x,'k','linewidth',2)
hold on
% subplot(2,1,1)
grid
plot( x4,'b'); % ,tt,x,'k'
legend('down-sampling by 5');
Here is you error:
tmax= length(x) ;
tt= 0:tmax -1;
x4 = x(1:5:end);
t1_n = 1:5:tt; % <---
tt is an array containing numbers 0 through tmax-1. Defining t1_n as t1_n = 1:5:tt will not create an array, but an empty matrix. Why? Expression t1_n = 1:5:tt will use only the first value of array tt, hence reduce to t1_n = 1:5:tt = 1:5:0 = <empty matrix>. Naturally, when you later on try to access t1_n as if it were an array (peak_time(k) = t1_n(i)), you'll get an error.
You probably want to exchange t1_n = 1:5:tt with
t1_n = 1:5:tmax;
You need to index the tt array correctly.
you can use
t1_n = tt(1:5:end); % note that this will give a zero based index, rather than a 1 based index, due to t1_n starting at 0. you can use t1_n = 1:tmax if you want 1 based (matlab style)
you can also cut down the code a little, there are some variables that dont seem to be used, or may not be necessary -- including the t1_n variable:
x=load('ww.txt');
tmax= length(x);
x4 = x(1:5:end);
xmin = 170
% now change the code
maxnopeaks = round(tmax/2);
peaks(maxnopeaks)=0; % preallocate the peaks for speed
index(maxnopeaks)=0; % preallocate index for speed
i = 0;
for n = 2 : tmax-1
if x(n) > xmin
if x(n) >= x(n-1) & x(n) >= x(n+1)
i = i+1;
peaks(i) = t(n);
index(i) = n;
end
end
end
% now trim the excess values (if any)
peaks = peaks(1:i);
index = index(1:i);

MATLAB: search for elements in an array matching multidimensional condition

I have a column vector (V1) of real numbers like:
123.2100
125.1290
...
954.2190
If I add, let's say, a number 1 to each row in this vector, I will get (V2):
124.2100
126.1290
...
955.2190
I need to find out how many elements from V2 are inside some error-window created from V1. For example the error-window = 0.1 (but in my case every element in V1 has it's own error window):
123.1100 123.3100
125.0290 125.2290
...
954.1190 954.3190
I can create some code like this:
% x - my vector
% ppm - a variable responsible for error-window
window = [(1-(ppm/1000000))*x, (1+(ppm/1000000))*x]; % - error-window
mdiff = 1:0.001:20; % the numbers I will iteratively add to x
% (like the number 1 in the example)
cdiff = zeros(length(mdiff),1); % a vector that will contain counts of elements
% corresponding to different mdiff temp = 0;
for i = 1:length(mdiff)
for j = 1:size(window,1)
xx = x + mdiff(i);
indxx = find( xx => window(j,1) & xx <= window(j,2) );
if any(indxx)
temp = temp + length(indxx); %edited
end
end
cdiff(i) = temp;
temp = 0;
end
So, at the end cdiff will contain all the counts corresponding to mdiff. The only thing, I would like to make the code faster. Or is there a way to avoid using the second loop (with j)? I mean to directly use a multidimensional condition.
EDIT
I decided to simpify the code like this (thanking to the feedback I got here):
% x - my vector
% ppm - a variable responsible for error-window
window = [(1-(ppm/1000000))*x, (1+(ppm/1000000))*x]; % - error-window
mdiff = 1:0.001:20; % the numbers I will iteratively add to x
% (like the number 1 in the example)
cdiff = zeros(length(mdiff),1); % a vector that will contain counts of elements
% corresponding to different mdiff temp = 0;
for i = 1:length(mdiff)
xx = x + mdiff(i);
cdiff(i) = sum(sum(bsxfun(#and,bsxfun(#ge,xx,window(:,1)'),bsxfun(#le,xx,window(:,2)'))));
end
In this case the code works faster and seems properly
add = 1; %// how much to add
error = .1; %// maximum allowed error
V2 = V1 + add; %// build V2
ind = sum(abs(bsxfun(#minus, V1(:).', V2(:)))<error)>1; %'// index of elements
%// of V1 satisfying the maximum error condition. ">1" is used to because each
%// element is at least equal to itself
count = nnz(ind);
Think this might work for you -
%%// Input data
V1 = 52+rand(4,1)
V2 = V1+1;
t= 0.1;
low_bd = any(abs(bsxfun(#minus,V2,[V1-t]'))<t,2); %%//'
up_bd = any(abs(bsxfun(#minus,V2,[V1+t]'))<t,2); %%//'
count = nnz( low_bd | up_bd )
One could also write it as -
diff_map = abs(bsxfun(#minus,[V1-t V1+t],permute(V2,[3 2 1])));
count = nnz(any(any(diff_map<t,2),1))
Edit 1:
low_bd = any(abs(bsxfun(#minus,V2,window(:,1)'))<t,2); %%//'
up_bd = any(abs(bsxfun(#minus,V2,window(:,2)'))<t,2); %%//'
count = nnz( low_bd | up_bd )
Edit 2: Vectorized form for the edited code
t1 = bsxfun(#plus,x,mdiff);
d1 = bsxfun(#ge,t1,permute(window(:,1),[3 2 1]));
d2 = bsxfun(#le,t1,permute(window(:,2),[3 2 1]));
t2 = d1.*d2;
cdiff_vect = max(sum(t2,3),[],1)';

Matlab solution for implicit finite difference heat equation with kinetic reactions

I am trying to model heat conduction within a wood cylinder using implicit finite difference methods. The general heat equation that I'm using for cylindrical and spherical shapes is:
Where p is the shape factor, p = 1 for cylinder and p = 2 for sphere. Boundary conditions include convection at the surface. For more details about the model, please see the comments in the Matlab code below.
The main m-file is:
%--- main parameters
rhow = 650; % density of wood, kg/m^3
d = 0.02; % wood particle diameter, m
Ti = 300; % initial particle temp, K
Tinf = 673; % ambient temp, K
h = 60; % heat transfer coefficient, W/m^2*K
% A = pre-exponential factor, 1/s and E = activation energy, kJ/mol
A1 = 1.3e8; E1 = 140; % wood -> gas
A2 = 2e8; E2 = 133; % wood -> tar
A3 = 1.08e7; E3 = 121; % wood -> char
R = 0.008314; % universal gas constant, kJ/mol*K
%--- initial calculations
b = 1; % shape factor, b = 1 cylinder, b = 2 sphere
r = d/2; % particle radius, m
nt = 1000; % number of time steps
tmax = 840; % max time, s
dt = tmax/nt; % time step spacing, delta t
t = 0:dt:tmax; % time vector, s
m = 20; % number of radius nodes
steps = m-1; % number of radius steps
dr = r/steps; % radius step spacing, delta r
%--- build initial vectors for temperature and thermal properties
i = 1:m;
T(i,1) = Ti; % column vector of temperatures
TT(1,i) = Ti; % row vector to store temperatures
pw(1,i) = rhow; % initial density at each node is wood density, rhow
pg(1,i) = 0; % initial density of gas
pt(1,i) = 0; % inital density of tar
pc(1,i) = 0; % initial density of char
%--- solve system of equations [A][T]=[C] where T = A\C
for i = 2:nt+1
% kinetics at n
[rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,T',pw(i-1,:));
pw(i,:) = pw(i-1,:) + rww.*dt; % update wood density
pg(i,:) = pg(i-1,:) + rwg.*dt; % update gas density
pt(i,:) = pt(i-1,:) + rwt.*dt; % update tar density
pc(i,:) = pc(i-1,:) + rwc.*dt; % update char density
Yw = pw(i,:)./(pw(i,:) + pc(i,:)); % wood fraction
Yc = pc(i,:)./(pw(i,:) + pc(i,:)); % char fraction
% thermal properties at n
cpw = 1112.0 + 4.85.*(T'-273.15); % wood heat capacity, J/(kg*K)
kw = 0.13 + (3e-4).*(T'-273.15); % wood thermal conductivity, W/(m*K)
cpc = 1003.2 + 2.09.*(T'-273.15); % char heat capacity, J/(kg*K)
kc = 0.08 - (1e-4).*(T'-273.15); % char thermal conductivity, W/(m*K)
cpbar = Yw.*cpw + Yc.*cpc; % effective heat capacity
kbar = Yw.*kw + Yc.*kc; % effective thermal conductivity
pbar = pw(i,:) + pc(i,:); % effective density
% temperature at n+1
Tn = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T);
% kinetics at n+1
[rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,Tn',pw(i-1,:));
pw(i,:) = pw(i-1,:) + rww.*dt;
pg(i,:) = pg(i-1,:) + rwg.*dt;
pt(i,:) = pt(i-1,:) + rwt.*dt;
pc(i,:) = pc(i-1,:) + rwc.*dt;
Yw = pw(i,:)./(pw(i,:) + pc(i,:));
Yc = pc(i,:)./(pw(i,:) + pc(i,:));
% thermal properties at n+1
cpw = 1112.0 + 4.85.*(Tn'-273.15);
kw = 0.13 + (3e-4).*(Tn'-273.15);
cpc = 1003.2 + 2.09.*(Tn'-273.15);
kc = 0.08 - (1e-4).*(Tn'-273.15);
cpbar = Yw.*cpw + Yc.*cpc;
kbar = Yw.*kw + Yc.*cpc;
pbar = pw(i,:) + pc(i,:);
% revise temperature at n+1
Tn = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T);
% store temperature at n+1
T = Tn;
TT(i,:) = T';
end
%--- plot data
figure(1)
plot(t./60,TT(:,1),'-b',t./60,TT(:,m),'-r')
hold on
plot([0 tmax/60],[Tinf Tinf],':k')
hold off
xlabel('Time (min)'); ylabel('Temperature (K)');
sh = num2str(h); snt = num2str(nt); sm = num2str(m);
title(['Cylinder Model, d = 20mm, h = ',sh,', nt = ',snt,', m = ',sm])
legend('Tcenter','Tsurface',['T\infty = ',num2str(Tinf),'K'],'location','southeast')
figure(2)
plot(t./60,pw(:,1),'--',t./60,pw(:,m),'-','color',[0 0.7 0])
hold on
plot(t./60,pg(:,1),'--b',t./60,pg(:,m),'b')
hold on
plot(t./60,pt(:,1),'--k',t./60,pt(:,m),'k')
hold on
plot(t./60,pc(:,1),'--r',t./60,pc(:,m),'r')
hold off
xlabel('Time (min)'); ylabel('Density (kg/m^3)');
The function m-file, funcACbar, that creates the system of equations to solve is:
% Finite difference equations for cylinder and sphere
% for 1D transient heat conduction with convection at surface
% general equation is:
% 1/alpha*dT/dt = d^2T/dr^2 + p/r*dT/dr for r ~= 0
% 1/alpha*dT/dt = (1 + p)*d^2T/dr^2 for r = 0
% where p is shape factor, p = 1 for cylinder, p = 2 for sphere
function T = funcACbar(pbar,cpbar,kbar,h,Tinf,b,m,dr,dt,T)
alpha = kbar./(pbar.*cpbar); % effective thermal diffusivity
Fo = alpha.*dt./(dr^2); % effective Fourier number
Bi = h.*dr./kbar; % effective Biot number
% [A] is coefficient matrix at time level n+1
% {C} is column vector at time level n
A(1,1) = 1 + 2*(1+b)*Fo(1);
A(1,2) = -2*(1+b)*Fo(2);
C(1,1) = T(1);
for k = 2:m-1
A(k,k-1) = -Fo(k-1)*(1 - b/(2*(k-1))); % Tm-1
A(k,k) = 1 + 2*Fo(k); % Tm
A(k,k+1) = -Fo(k+1)*(1 + b/(2*(k-1))); % Tm+1
C(k,1) = T(k);
end
A(m,m-1) = -2*Fo(m-1);
A(m,m) = 1 + 2*Fo(m)*(1 + Bi(m) + (b/(2*m))*Bi(m));
C(m,1) = T(m) + 2*Fo(m)*Bi(m)*(1 + b/(2*m))*Tinf;
% solve system of equations [A]{T} = {C} where temperature T = [A]\{C}
T = A\C;
end
And finally the function that deals with the kinetic reactions, funcY, is:
% Kinetic equations for reactions of wood, first-order, Arrhenious type equations
% K = A*exp(-E/RT) where A = pre-exponential factor, 1/s
% and E = activation energy, kJ/mol
function [rww, rwg, rwt, rwc] = funcY(A1,E1,A2,E2,A3,E3,R,T,pww)
K1 = A1.*exp(-E1./(R.*T)); % wood -> gas (1/s)
K2 = A2.*exp(-E2./(R.*T)); % wood -> tar (1/s)
K3 = A3.*exp(-E3./(R.*T)); % wood -> char (1/s)
rww = -(K1+K2+K3).*pww; % rate of wood consumption (rho/s)
rwg = K1.*pww; % rate of gas production from wood (rho/s)
rwt = K2.*pww; % rate of tar production from wood (rho/s)
rwc = K3.*pww; % rate of char production from wood (rho/s)
end
Running the above code gives a temperature profile at the center and surface of the wood cylinder:
As you can see from this plot, for some reason the center and surface temperatures rapidly converge at the 2 min mark which isn't correct.
Any suggestions on how to fix this or create a more efficient way to solve the problem?
It looks like you are using a backward Euler implicit method of discretization of a diffusion PDE. A more accurate approach is the Crank-Nicolson method. Both methods are unconditionally stable.
The introduction of a T-dependent diffusion coefficient requires special treatment, best probably in the form of linearization, as explained briefly here. It would be useful to identify stability criteria to ensure that the time and distance step lengths are appropriate following introduction of T-dependent coefficients.
Note that matlab offers a PDE toolbox which might be useful to you, although I have not checked how you might use it in detail.

Resources