How to keep certain numbers in a cell array?

3 ビュー (過去 30 日間)
Nabil Abdullah
Nabil Abdullah 2017 年 4 月 17 日
コメント済み: Jan 2017 年 4 月 18 日
Lets say for example I have a cell array A = {1,2,3},{4,5,6},{7,8,9},{10,11,12}. I am then given the string B = [1,3,5,12]. How would I create an output cell array where the numbers which were not mentioned in the string B were removed? i.e ans = {1,3} {5} {12}
Thank you for your time
Nabil
  2 件のコメント
Jan
Jan 2017 年 4 月 17 日
編集済み: Jan 2017 年 4 月 17 日
What have you tried so far? Which problems occur?
A = {1,2,3},{4,5,6},{7,8,9},{10,11,12}
This is not a cell array and no valid Matlab code. Please do not let use guess which input you have. Is this:
A = {[1,2,3], [4,5,6], [7,8,9], [10,11,12]}
or
A = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}
?
Nabil Abdullah
Nabil Abdullah 2017 年 4 月 17 日
編集済み: Nabil Abdullah 2017 年 4 月 17 日
my bad its the second one, A = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}, also the ans would be {{1,3},{5},{12}}
I have tried doing the below:
y = {};
for i = 1:length(A)
C = A{i}
for j = B
if length(intersect(B,C)) == 1
y{end+1} = {intersect(B,C)}
end
end
end

サインインしてコメントする。

採用された回答

Jan
Jan 2017 年 4 月 17 日
編集済み: Jan 2017 年 4 月 17 日
A = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
B = [1,3,5,12];
R = cell(size(A));
for iA = 1:numel(A)
v = cat(2, A{iA}{:}); % A{iA} as vector
ex = ismember(v, B);
R{iA} = A{iA}(ex);
end
R = R(~cellfun('isempty', R));
Or:
R = cell(size(A));
iR = 0;
for iA = 1:numel(A)
v = cat(2, A{iA}{:}); % A{iA} as vector
ex = ismember(v, B);
if any(ex)
iR = iR + 1;
R{iR} = A{iA}(ex);
end
end
R = R(1:iR);
  2 件のコメント
Nabil Abdullah
Nabil Abdullah 2017 年 4 月 18 日
編集済み: Nabil Abdullah 2017 年 4 月 18 日
I see, I'm not familiar with the ismember function. If you dont mind me asking, would the above code still work if A = {[1,2,3], [4,5,6], [7,8,9], [10,11,12]}? and what would I have to change if I wanted the output ans = {[1,3] [5] [ ] [12]}? is this even possible
Jan
Jan 2017 年 4 月 18 日
To keep the empty matrix in the output, remove the "R = R(~cellfun(..." line from the 1st code. You can try by your own, if the code works for the wanted input.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by