查找元胞数组中所有(非唯一)元素的索引,因为它们出现在第二个(已排序且唯一)元胞数组中 [英] Find index of all (non-unique) elements in a cell array as they appear in a second (sorted and unique) cell array

查看:8
本文介绍了查找元胞数组中所有(非唯一)元素的索引,因为它们出现在第二个(已排序且唯一)元胞数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A = {'A'; 'E'; 'A'; 'F'};

B = {'A';'B';'C';'D';'E'; 'F'};

我试图为单元格数组A 中的每个字符串获取与单元格数组B 中的该字符串匹配的索引.A 会有重复的值,B 不会.

I am trying to get for each string in cell array A, the index that matches that string in cell array B. A will have repeated values, B will not.

find(ismember(B, A) == 1)

输出

1
5
6 

但我想得到

1
5
1
6

最好在一个班轮中.我也不能使用 strcmp 代替 ismember,因为向量的大小不同.

preferably in a one liner. I can't use strcmp instead of ismember either as the vectors are different sizes.

向量实际上将包含日期字符串,我需要索引而不是逻辑索引矩阵,我对数字感兴趣,不要将其用于索引.

The vectors will actually contain date strings, and I need the index not a logical index matrix, I'm interested in the number not to use it for indexing.

我该怎么做?

推荐答案

将参数翻转为 ismember,然后使用第二个输出参数:

You flip the arguments to ismember, and you use the second output argument:

[~,loc]=ismember(A,B)

loc =

     1
     5
     1
     6

第二个输出告诉你 A 的元素在 B 中的位置.

The second output tells you where the elements of A are in B.

如果您对代码中的行数有非常严格的限制,并且无法解雇施加此类限制的经理,您可能需要访问 ismember<的第二个输出/code> 直接.为此,您可以创建以下帮助函数,允许直接访问函数的第 i 个输出

If you are working with very strict limits to how many lines you can have in your code, and are in no position to fire the manager who imposed such limitations, you may want to access the second output of ismember directly. In order to do this, you can create the following helper function that allows to directly access the i-th output of a function

function out = accessIthOutput(fun,ii)
%ACCESSITHOUTPUT returns the i-th output variable of the function call fun
%
% define fun as anonymous function with no input, e.g.
% @()ismember(A,B)
% where A and B are defined in your workspace
%
% Using the above example, you'd access the second output argument
% of ismember by calling
% loc = accessIthOutput(@()ismember(A,B),2)


%# get the output
[output{1:ii}] = fun();

%# return the i-th element
out = output{ii};

这篇关于查找元胞数组中所有(非唯一)元素的索引,因为它们出现在第二个(已排序且唯一)元胞数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆