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

如何基于字符串名称返回元胞数组?附分析所得示例元胞数组A

Extract Matching Elements from Cell Array by Name String

Hey there! Based on your example cell array A, here are a few straightforward ways to retrieve the corresponding cell(s) using the name string:


1. Exact Match with Vectorized Lookup (Most Efficient)

If you need an exact match for the name string, use strcmp to create a logical index, then index into A:

% Define the target name you're looking for
targetName = 'Upper_lower_torque/REV--Lower torque.1';

% Create logical index where the first element of each cell matches targetName
matchIdx = strcmp(cellfun(@(x) x{1}, A), targetName);

% Get the matching cell(s)
matchingCells = A(matchIdx);

How this works:

  • cellfun(@(x) x{1}, A) extracts all the name strings from the first position of each cell in A.
  • strcmp(..., targetName) compares each extracted string to your target, returning a boolean array where true means a match.
  • A(matchIdx) pulls out all cells that match the target name.

2. Simple Loop (Great for Beginners)

If you prefer a more explicit approach, loop through each element in A and check for matches:

targetName = 'Upper_lower_torque/SPH-Lower torque-Upper torque.1';
matchingCells = {};

for i = 1:length(A)
    if strcmp(A{i}{1}, targetName)
        matchingCells{end+1} = A{i};
    end
end

This builds a new cell array matchingCells containing all elements where the name matches your target.


3. Partial Match (If You Don't Need Exact Strings)

If you want to find all cells where the name contains a specific substring, use contains instead of strcmp:

targetSubstring = 'Lower torque';
matchIdx = contains(cellfun(@(x) x{1}, A), targetSubstring);
matchingCells = A(matchIdx);

This will return both elements from your example, since both names include "Lower torque".


Notes:

  • If multiple cells match your target, matchingCells will be a cell array of all those matches. If only one matches, it'll be a 1x1 cell array (you can access the force/torque data with matchingCells{1}{3}).
  • Always check isempty(matchingCells) to handle cases where no matches are found and avoid errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:59:15