Assigning many cell array entries to same value using index

25 次查看(过去 30 天)
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,15:31
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,15:31
编辑:Matt J 2024-7-9,15:32
Another way,
[cellArray{iHigh}] = deal('High');
[cellArray{iLow}] = deal('Low');

Matt J
Matt J 2024-7-9,15:37
编辑:Matt J 2024-7-9,15:41
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);

标签

Community Treasure Hunt

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

Start Hunting!

Translated by