Assigning many cell array entries to same value using index

26 Ansichten (letzte 30 Tage)
KAE
KAE am 9 Jul. 2024
Kommentiert: KAE am 9 Jul. 2024
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.

Akzeptierte Antwort

Image Analyst
Image Analyst am 9 Jul. 2024
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'};

Weitere Antworten (2)

Matt J
Matt J am 9 Jul. 2024
Bearbeitet: Matt J am 9 Jul. 2024
Another way,
[cellArray{iHigh}] = deal('High');
[cellArray{iLow}] = deal('Low');

Matt J
Matt J am 9 Jul. 2024
Bearbeitet: Matt J am 9 Jul. 2024
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);

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by