Matrix processing problem; creating new matrix

1 view (last 30 days)
Hi,
I have the following experimental set up. An object is able to move between three areas (A, B and C). It can only access C via B.
I am interested in knowing at what point the object moved from C to B, and then whether it moved onto A or back to C.
i.e. if the data matrix looked like the following:
0 0 0
0 0 1
0 1 0
0 1 0
1 0 0
0 1 0
0 1 0
0 0 1
0 1 0
0 0 1
0 0 1
0 0 0
I would want to output a new matrix:
0
0
1 (marking C to B transition)
0
2 (marking B to A transition, following a C to B transition)
0
0
0
1 (marking C to B transition)
3 (marking B to C transition, following a C to B transition)
0
0
I already have the following code to mark transitions from C to B:
matrix =[0 0; 0 1; 1 0; 0 1; 0 1; 0 1; 1 0]; % column 1 = B, column 2 = C
if matrix(1,1)
output1 = nan;
else
output1 = 0;
end
output2end = matrix(2:end,1) & matrix(1:end-1,2);
output_Cage1 = [output1; output2end];
output_Cage1 =
0
0
1
0
0
0
1
But I am not sure how to extend this to work for 3 columns. Any help would be much appreciated. Many thanks.

Accepted Answer

Kevin Holly
Kevin Holly on 16 Jan 2023
Edited: Kevin Holly on 16 Jan 2023
matrix = [0 0 0
0 0 1
0 1 0
0 1 0
1 0 0
0 1 0
0 1 0
0 0 1
0 1 0
0 0 1
0 0 1
0 0 0];
if matrix(1,1)
output1 = nan;
else
output1 = 0;
end
output2end = matrix(2:end,2) & matrix(1:end-1,3);
output_Cage1 = [output1; output2end] % C to B
output_Cage1 = 12×1
0 0 1 0 0 0 0 0 1 0
% Identify all B to A
output2end = matrix(2:end,1) & matrix(1:end-1,2);
output_Cage2 = output_Cage1+[output1; 2*output2end] % B to A
output_Cage2 = 12×1
0 0 1 0 2 0 0 0 1 0
% Identify all B to C
output2end = matrix(2:end,3) & matrix(1:end-1,2);
output_Cage3 = output_Cage2+[output1; 3*output2end] % B to C
output_Cage3 = 12×1
0 0 1 0 2 0 0 3 1 3
% Remove B to C or B to A that does not follow C to B
for ii = 1:length(output_Cage3) % iteratively go through array
if output_Cage3(ii) == 1 % if C to B happens, then set count to 1
count = 1;
elseif output_Cage3(ii) ~= 0 % if the value is not 0 or 1
if count == 0 % and count is 0 (no previous C to B detected)
output_Cage3(ii) = 0; % then remove the B to C or B to A present
end
count = 0; % set count back to 0 indicating that there is no previous C to B.
end
end
output_Cage3
output_Cage3 = 12×1
0 0 1 0 2 0 0 0 1 3
  16 Comments
Laura Steel
Laura Steel on 3 Feb 2023
Ah, I see, thanks. I do not have a function called count, but I hadn't created a variable called "count" prior to the loop. When I create count before hand, it then runs properly. I am assuming I should set count to 0 when I define it? Many thanks!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!