Assigning many cell array entries to same value using index

조회 수: 26 (최근 30일)
KAE
KAE 2024년 7월 9일
댓글: KAE 2024년 7월 9일
I would like to use an index to assign many entries in a cell array to the same value, but this example does not work. What should I be doing differently?
%% Goal is cell array 'cellArray' containing 'High' for certain elements, and 'Low' for other elements
% Create the index
a = rand(100, 1);
iHigh = a > 0.5; % Index to many values
iLow = a <= 0.5; % Index to many other values
% Assign the cell values based on the index
cellArray{iHigh} = 'High';
cellArray{iHigh} = 'Low';
% Gives error
% Assigning to 54 elements using a simple assignment statement is not supported. Consider using
% comma-separated list assignment.
cellArray(iHigh) = 'High';
cellArray(iLow) = 'Low';
% Gives error
% Unable to perform assignment because the indices on the left side are not compatible with the size of
% the right side.

채택된 답변

Image Analyst
Image Analyst 2024년 7월 9일
Seems like it should work, but it doesn't. However this works:
%% Goal is cell array 'cellArray' containing 'High' for certain elements, and 'Low' for other elements
% Create the index
a = rand(100, 1);
cellArray = cell(100, 1); % Initialize cell array
iHigh = a > 0.5; % Index to many values
iLow = a <= 0.5; % Index to many other values
% Assign the cell values based on the index.
% Put a cell into an element of an array that is a cell.
cellArray(iHigh) = {'High'};
cellArray(iLow) = {'Low'};

추가 답변 (2개)

Matt J
Matt J 2024년 7월 9일
편집: Matt J 2024년 7월 9일
Another way,
[cellArray{iHigh}] = deal('High');
[cellArray{iLow}] = deal('Low');

Matt J
Matt J 2024년 7월 9일
편집: Matt J 2024년 7월 9일
You should probably be using strings or catgorical arrays instead of cells. Regardless, it is easy to switch back and forth:
cellArray=string(cellArray);
cellArray(iHigh) = 'High';
cellArray(iLow) = 'Low';
cellArray=cellstr(cellArray);

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by