Matrix processing problem; creating new matrix

조회 수: 2 (최근 30일)
Laura Steel
Laura Steel 2023년 1월 16일
댓글: Kevin Holly 2023년 2월 3일
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.

채택된 답변

Kevin Holly
Kevin Holly 2023년 1월 16일
편집: Kevin Holly 2023년 1월 16일
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
Laura Steel
Laura Steel 2023년 2월 3일
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!
Kevin Holly
Kevin Holly 2023년 2월 3일
Yes, that is right.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by