Manipulating Data In 3D & 4D matrices based on distinct conditions
Show older comments
I've a 3D array 'Q' with specified dimensions (as a simple case, assume: 5 X 7 X 4) with integer values, and I've another corresponding matrix 'R' (size: 5 X 7) with values between 0-3 <I commented it in code in 3 dimensions, in case required>. The 3rd dimension (page) in Q-matrix (4) is basically 'time'; initial conditions are supplied at t = 1 i.e: for Q(:,:,1). The subsequent values in Q are spacial as well as time dependent and will be evaluated according to an equation. <For simplicity, assume the equation below in code>
I want equation-A to be implemented for the index locations in Q where values in R = 1 or R = 3
& I want Equ-B to be implemented for the index locations in Q where values in R = 0.
I know the concept of logical/linear indexing... and using that I can write something like this in nested for loops ():
q_latest = Q(:,:,t);
q_prev = Q(:,:,t-1);
q_latest(R == 1 | R == 3) = q_prev(R == 1 | R == 3) + {*** something I don't know how to write***}/alpha
Q(:,:,t) = q_latest;
Real problem lies in the spatial part of code line above where I'm walking in space coordinates (i-1,j)/(1,j+1) etc alongwith time (t-1) in loop iteration... Can anybody please help in this regard? In case I've to use matrix 'R' in 3D form instead of 2D form then still in that case how will it be done? I will actually implement it in 4D so in that case what should be done (there should be some general strategy which I'm missing)? If I have to get rid of nested for-loops by vectorizing everything, is there any way to do so?
% ********* Sample Code ********* %
Q = randi(10,[5 7 4])
R = zeros([5 7]);
R(2:4,2:3) = 1;
R(3:4,4:5) = 2;
R(2:4,6) = 3;
% R = repmat(R, 1, 1, 4); % For R matrix in 3D
[r c T] = size(Q);
alpha = 1; beta = 2; gamma = 3; kappa = 4;
for t = 2:T
for i = 2:r-1
for j = 2:c-1
% Equ-A
Q(i,j,t) = Q(i,j,t-1) + (Q(i-1,j,t-1)+Q(i+1,j,t-1))/alpha;
% Equ-B
Q(i,j,t) = beta*Q(i,j,t-1) + gamma*(Q(i,j-1,t-1)+Q(i,j+1,t-1));
end
end
end
Answers (1)
I think this is what you want.
kernelA=[1/alpha;1;1/alpha];
kernelB=[gamma, beta, gamma];
RA=(R==1 | R==3);
RB=(R==0);
for t = 2:T
qprev = Q(:,:,t-1);
qlatest=Q(:,:,t);
EquA=convn(qprev,kernelA,'same');
EquB=convn(qprev,kernelB,'same');
qlatest(RA)=EquA(RA);
qlatest(RB)=EquB(RB);
Q(:,:,t)=qlatest;
end
2 Comments
Adeel
on 5 Aug 2023
Matt J
on 5 Aug 2023
In fact my actual equation is something different; (it is a numerical derivative equation basically)
That doesn't sound different. A numerical derivative is implementable by a convolution.
Also, I wanted a general approach for any dimension problem
The approach I showed you would apply to any dimension. The only thing that would change is the number of indices used to obtain qprev and qlatest.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!