首页 > 解决方案 > 如何在 MATLAB 上的矩阵的列中找到三个连续的 1?

问题描述

clear;
M = readmatrix('a51.xlsx','Sheet','Sheet1','Range','B2:H13'); %the number '51' represents a student's ID.
M(8:12,1)=51; %This is the location of sets of three consecutive '1's
M(5,2)=51;

我想让代码找到矩阵列中连续三个“1”的位置。以上是我们自己找到后告诉代码的。

z1=num2cell(M);
ID51={'Open Hours';'9:00';'10:00';'11:00';'12 noon';'1:00 p.m.';'2:00';'3:00';'4:00';'5:00';'6:00';'7:00';'8:00'};
a51={'Sun';[];[];[];[];[];[];[];[];[];[];[];[]};
b51={'Mon';[];[];[];[];[];[];[];[];[];[];[];[]};
c51={'Tues';[];[];[];[];[];[];[];[];[];[];[];[]};
d51={'Wed';[];[];[];[];[];[];[];[];[];[];[];[]};
e51={'Thur';[];[];[];[];[];[];[];[];[];[];[];[]};
f51={'Fri';[];[];[];[];[];[];[];[];[];[];[];[]};
g51={'Sat';[];[];[];[];[];[];[];[];[];[];[];[]};
L51 = table(ID51,a51,b51,c51,d51,e51,f51,g51);
Table1 = table2array(L51);
Table1(1:12,2:8)=z1;
writecell(Table1,'51Library.xlsx','Sheet',1); %creates the excel file for student 1 during the semester

上面是我们用来创建 Excel 工作表的代码,其中工作日标记列,时间标记行,以及标题。有什么办法可以浓缩吗?也许可读?如上所示,我们的数据被保存到一个矩阵中。

标签: excelmatlabdebuggingmatrix

解决方案


要找到三个连续的 1:假设您有以下列数据:

A = [2; 5; 6; 3; 4; 1; 1; 2; 3; 1; 1; 1; 7; 9; 10];

然后,通过使用Mask,您可以定义任何逻辑(在您的情况下:三个连续的 1):

Mask = @(x)  (x(1) == 1) && (x(2) == 1) && (x(3) == 1); 

搜索数组或矩阵以查看上面的 Mask 在哪里为真:

Idx = [];
for ii = 1:length(A)-3
   if (Mask(A(ii:ii+2))
      Idx = [Idx, ii];
   end
end

推荐阅读