单元格到矩阵匹配/映射/单元格操作 (MATLAB)

发布于 2024-10-07 18:01:04 字数 437 浏览 2 评论 0原文

我无法使用下面的数据找到与 FinalAnswer 等效的字符串。拜托,我不能使用 if/for 循环!最终答案是每个元素作为数组(即 mainData 的格式)

mainData = {'IBM' [201] [1] ; 
            'GE' [403] [1] ; 
            'MSFT' [502] [3] ;
            'GM' [101] [2]       } ;

finalAns = [ 101 2 0.5; 403 1 0.6 ]                  ;

%% I tried doing this ->
temp = cell2mat(mainData(:,[2 3])) ;

tf = ismember(temp, finalAns(:,[1 2],'rows') ;
secIDs = mainData(tf) ;

I cannot find the string equivalent of the finalAnswer using the data below. Please, I cannot use if/for loops! A final answer is preferred with each element as an array (i.e. the format of mainData)

mainData = {'IBM' [201] [1] ; 
            'GE' [403] [1] ; 
            'MSFT' [502] [3] ;
            'GM' [101] [2]       } ;

finalAns = [ 101 2 0.5; 403 1 0.6 ]                  ;

%% I tried doing this ->
temp = cell2mat(mainData(:,[2 3])) ;

tf = ismember(temp, finalAns(:,[1 2],'rows') ;
secIDs = mainData(tf) ;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绮烟 2024-10-14 18:01:05

为了获取 mainData 的每一行中与 finalAns 中的条目相匹配的条目(基于 mainData 的最后两列和前两列) finalAns 的列),并按照它们在 finalAns 中出现的顺序获取它们,并附加 finalAns 的最后一列,您可以这样做this:

>> temp = cell2mat(mainData(:,2:3));
>> [isThere,index] = ismember(finalAns(:,1:2),temp,'rows');
>> output = [mainData(index(isThere),:) num2cell(finalAns(isThere,3))]

output = 

    'GM'    [101]    [2]    [0.5000]
    'GE'    [403]    [1]    [0.6000]

输出是一个 2×4 元胞数组,每个值都位于单独的元胞中。如果您希望将最后三列收集在向量中,则可以将上面的 output 计算替换为:

>> temp = [temp(index(isThere),:) finalAns(isThere,3)];
>> output = [mainData(index(isThere),1) num2cell(temp,2)]

output = 

    'GM'    [1x3 double]
    'GE'    [1x3 double]

请注意,现在您有一个 2×2 元胞数组,其中第二个元胞中的单元格列包含 1×3 双精度数组。

In order to get the entries in each row of mainData that match those in finalAns (based on the last two columns of mainData and the first two columns of finalAns) and to get them in the same order that they appear in finalAns and with the last column of finalAns appended, you can do this:

>> temp = cell2mat(mainData(:,2:3));
>> [isThere,index] = ismember(finalAns(:,1:2),temp,'rows');
>> output = [mainData(index(isThere),:) num2cell(finalAns(isThere,3))]

output = 

    'GM'    [101]    [2]    [0.5000]
    'GE'    [403]    [1]    [0.6000]

The output is a 2-by-4 cell array with each value in a separate cell. If you want the last three columns to be collected in a vector, you can replace the calculation of output above with this:

>> temp = [temp(index(isThere),:) finalAns(isThere,3)];
>> output = [mainData(index(isThere),1) num2cell(temp,2)]

output = 

    'GM'    [1x3 double]
    'GE'    [1x3 double]

Note that now you have a 2-by-2 cell array where cells in the second column contain 1-by-3 double arrays.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文