根据标记值从大型单个阵列创建子阵列

时间:2013-06-24 02:25:15

标签: arrays matlab

我需要创建一个二维数组的一维数组,这样程序就可以分别读取每个二维数组。

我有一个包含5列的大型数组,第二列存储'marker'数据。根据标记值,我需要从剩余的4列中获取相应的数据,并将它们自己放入一个新的数组中。

我在考虑运行两个for循环,一个用于获取目标数据并将其写入一维数组中的一个单元格,另一个用于逐行读取初始数组,以查找标记。

我觉得这是一个相当简单的问题,我只是在弄清楚如何基本上剪切和粘贴数组的某些部分并将它们写入新的部分。

提前致谢。

2 个答案:

答案 0 :(得分:1)

不需要 for循环,请将您的标记与logical indexing一起使用。例如,如果 large 数组为A

B=A(A(:,2)==marker,[1 3:5]) 

将选择标记所在的所有行,而不选择第2列。然后,您可以使用reshape(:)运算符将其设为1D,例如

B=B(:)

或者,如果你想要一个单行:

B=reshape(A(A(:,2)==marker,[1 3:5]),1,[]); 

答案 1 :(得分:0)

我正在回答我自己的问题,向潜在的未来用户展示我最终提出的解决方案。

%=======SPECIFY CSV INPUT FILE HERE========
MARKER_DATA=csvread('ESphnB2.csv');                        % load data from csv file
%===================================

A=MARKER_DATA(:,2);                                         % create 1D array for markers
A=A';                                                       % make column into row

for i=1:length(A)                                           % for every marker
    if A(i) ~= 231                                          % if it is not 231 then
        A(i)=0;                                             % set value to zero
    end
end

edgeArray = diff([0; (A(:) ~= 0); 0]);                      % set non-zero values to 1
ind = [find(edgeArray > 0) find(edgeArray < 0)-1];          % find indices of 1 and save to array with beginning and end

t=1;                                                        % initialize counter for trials
for j=1:size(ind,1)                                         % for every marked index
    B{t}=MARKER_DATA(ind(j,1):ind(j,2),[3:6]);              % create an array with the rows from the data according to indicies
    t=t+1;                                                  % create a new trial
end

gazeVectors=B';                                             % reorient and rename array of trials for saccade analysis

%======SPECIFY MAT OUTPUT FILE HERE===
save('Trial_Data_2.mat','gazeVectors');                       % save array to mat file
%=====================================