フィルターのクリア

Assigning many cell array entries to same value using index

25 ビュー (過去 30 日間)
KAE
KAE 2024 年 7 月 9 日 15:19
コメント済み: KAE 2024 年 7 月 9 日 15:57
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'};
  1 件のコメント
KAE
KAE 2024 年 7 月 9 日 15:57
Thanks. It even works without initializing cellArray.

サインインしてコメントする。

その他の回答 (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