gpt4 book ai didi

matlab - 检查单元格内的成员

转载 作者:行者123 更新时间:2023-12-02 04:49:01 24 4
gpt4 key购买 nike

我有一个元胞数组(data),如下所示(此处缩短):

'45.203885' '-90.600123'    '119-8001'  733144  NaN
'45.203885' '-90.600123' '119-8001' 733147 NaN
'45.203885' '-90.600123' '119-8001' 733150 NaN
'45.203885' '-90.600123' '119-8001' 733153 NaN
'45.203885' '-90.600123' '119-8001' 733156 NaN
'45.203885' '-90.600123' '119-8001' 733159 NaN

我想根据第 4 列(已使用 datenum 转换的日期)是否匹配 来填充 NaN 的第 5 列B.

B(也是一个单元格)看起来像这样(为了使示例有意义,也缩短了很多):

'45.203885' '-90.600123'    '119-8001'  733144  '3.3'
'45.203885' '-90.600123' '119-8001' 733150 '9.5'
'45.203885' '-90.600123' '119-8001' 733156 '6.8'

如您所见,B 中的第 4 列日期并不一致。我正在尝试将 NaN 添加到第 5 列,其中 B(:,3)B(:, 4) 不添加匹配 data(:,3)data(:, 4)

最终产品应该类似于:

'45.203885' '-90.600123'    '119-8001'  733144  '3.3'
'45.203885' '-90.600123' '119-8001' 733147 NaN
'45.203885' '-90.600123' '119-8001' 733150 '9.5'
'45.203885' '-90.600123' '119-8001' 733153 NaN
'45.203885' '-90.600123' '119-8001' 733156 '6.8'
'45.203885' '-90.600123' '119-8001' 733159 NaN

如果data是一个矩阵,我只需执行以下操作:

data_ind = ismember(data(:,3:4),B(:,3:4),'rows');

但我不知道如何用单元格做到这一点。某种形式的 cellfun 可以解决这个问题吗?

最佳答案

sd = size(data,1); %// number of rows of data
sb = size(B,1); %// number of rows of B
[dd bb] = ndgrid(1:sd,1:sb); %// all combinations (row of data, row of B)
cond1 = strcmp(data(dd,3),B(bb,3)); %// test col 3 for all combinations
cond2 = [data{dd,4}].'==[B{bb,4}].'; %// test col 4 for all combinations
cond = reshape(cond1 & cond2, sd, sb); %// combine the two conditions
[ib, id] = max(cond); %// id contains the index of the first 1 (if any) ...
%// ... of each col in cond; and ib is a logical index of the row of that 1
id = id(ib); %// keep only id for which the maximum is 1
data(id,:) = B(ib,:); %// copy matching rows of B into data

dataB 都包含与另一个变量的任何行都不匹配的行的示例:

data = {
'45.203885' '-90.600123' '119-8001' 733144 NaN
'45.203885' '-90.600123' '119-8001' 733147 NaN
'45.203885' '-90.600123' '119-8001' 733150 NaN
'45.203885' '-90.600123' '119-8001' 733153 NaN
'45.203885' '-90.600123' '119-8001' 733156 NaN
'45.203885' '-90.600123' '119-8001' 733159 NaN};

B = {
'45.203885' '-90.600123' '119-8001' [733144] '3.3'
'45.203885' '-90.600123' '119-8001' [733150] '9.5'
'45.203885' '-90.600123' '119-8001' [733156] '6.8'
'45.203885' '-90.600123' '169-8001' [833156] '6.8'};

结果:

data = 

'45.203885' '-90.600123' '119-8001' [733144] '3.3'
'45.203885' '-90.600123' '119-8001' [733147] [NaN]
'45.203885' '-90.600123' '119-8001' [733150] '9.5'
'45.203885' '-90.600123' '119-8001' [733153] [NaN]
'45.203885' '-90.600123' '119-8001' [733156] '6.8'
'45.203885' '-90.600123' '119-8001' [733159] [NaN]

关于matlab - 检查单元格内的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21412553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com