matlab 左键状态,在MATLAB中左键连接单元格数组

我在MATLAB中有2个单元格数组,例如:

A= {jim,4,paul,5 ,sean ,5,rose, 1}

第二个:

B= {jim, paul, george, bill, sean ,rose}

我想做一个SQL左连接,所以我将得到B中的所有值和它们与A的匹配.如果它们没有出现在A中,那么它将为’0′.手段:

C= {jim, 4, paul, 5, george, 0, bill, 0, sean, 5, rose, 1}

没有找到任何相关的帮助功能.

谢谢.

最佳答案 方法#1

%// Inputs

A= {'paul',5 ,'sean' ,5,'rose', 1,'jim',4}

B= {'jim', 'paul', 'george', 'bill', 'sean' ,'rose'}

%// Reshape A to extract the names and the numerals separately later on

Ar = reshape(A,2,[]);

%// Account for unsorted A with respect to B

[sAr,idx] = sort(Ar(1,:))

Ar = [sAr ; Ar(2,idx)]

%// Detect the presence of A's in B's and find the corresponding indices

[detect,pos] = ismember(B,Ar(1,:))

%// Setup the numerals for the output as row2

row2 = num2cell(zeros(1,numel(B)));

row2(detect) = Ar(2,pos(detect)); %//extracting names and numerals here

%// Append numerals as a new row into B and reshape as 1D cell array

out = reshape([B;row2],1,[])

代码运行 –

A =

'paul' [5] 'sean' [5] 'rose' [1] 'jim' [4]

B =

'jim' 'paul' 'george' 'bill' 'sean' 'rose'

out =

'jim' [4] 'paul' [5] 'george' [0] 'bill' [0] 'sean' [5] 'rose' [1]

方法#2

如果您希望将单元格数组中的数字用作字符串,则可以使用此修改后的版本 –

%// Inputs [Please edit these to your actual inputs]

A= {'paul',5 ,'sean' ,5,'rose', 1,'jim',4};

B= {'jim', 'paul', 'george', 'bill', 'sean' ,'rose'}

%// Convert the numerals into string format for A

A = cellfun(@(x) num2str(x),A,'Uni',0)

%// Reshape A to extract the names and the numerals separately later on

Ar = reshape(A,2,[]);

%// Account for unsorted A with respect to B

[sAr,idx] = sort(Ar(1,:));

Ar = [sAr ; Ar(2,idx)];

%// Detect the presence of A's in B's and find the corresponding indices

[detect,pos] = ismember(B,Ar(1,:));

%// Setup the numerals for the output as row2

row2 = num2cell(zeros(1,numel(B)));

row2 = cellfun(@(x) num2str(x),row2,'Uni',0); %// Convert to string formats

row2(detect) = Ar(2,pos(detect)); %//extracting names and numerals here

%// Append numerals as a new row into B and reshape as 1D cell array

out = reshape([B;row2],1,[])

代码运行 –

B =

'jim' 'paul' 'george' 'bill' 'sean' 'rose'

A =

'paul' '5' 'sean' '5' 'rose' '1' 'jim' '4'

out =

'jim' '4' 'paul' '5' 'george' '0' 'bill' '0' 'sean' '5' 'rose' '1'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值