You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MATLAB中ismember函数处理nx1字符数组查找空格异常问题

Fixing ismember for nx1 Cell Arrays of Characters in MATLAB

Let's break down why your current approach isn't working and how to fix it:

The Root Cause

When you convert a string array (like your String2) using convertStringsToChars, you don't get a 2D character array—you get a nx1 cell array, where each cell contains a separate character array.

Your original working example used a single character array, so ismember worked as expected. But for the cell array:

  • In Plan A, ismember(Char2, StringSearchedSpaces) compares entire cell elements (each being a character array) to a single space character, which will always return false (0).
  • In Plan B, Char2(z,:) accesses the cell container instead of the actual character array inside it—you need curly braces {} to pull out the content of each cell.

Corrected Solutions

Option 1: Fixed For Loop

Update your Plan B to use curly braces to access each cell's character array:

StringSearchedSpaces = ' '; % White space
String2 = ["Random info in middle one, "+ ...
"Random info still continues. ", "Random info in middle two. "+ ...
"Random info still continues. "];
Char2 = convertStringsToChars(String2);

% Fixed Plan B
PlanBString2Spaceidx = cell(size(Char2)); % Initialize cell array to store results
for z = 1:length(Char2)
    PlanBString2Spaceidx{z} = ismember(Char2{z}, StringSearchedSpaces);
end

This stores a logical array in each cell of PlanBString2Spaceidx, matching your working example: each array has 1s where spaces are present, 0s elsewhere.

Option 2: Simplify with cellfun

You can skip the manual loop using cellfun, which applies a function to every element of a cell array:

% Clean alternative with cellfun
Spaceidx = cellfun(@(x) ismember(x, StringSearchedSpaces), Char2, 'UniformOutput', false);

The 'UniformOutput', false argument tells MATLAB to return a cell array of results (since each character array might have a different length).

Verifying the Result

To confirm it's working, display one of the results:

% Show logical array for the first string
disp(Spaceidx{1})

You'll see 1s in positions where spaces exist, identical to the behavior of your 1x1 example.

内容的提问来源于stack exchange,提问作者Div

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:07:42