Matrix‎ > ‎cell array‎ > ‎

Single value to multiple fields

How to assign a single value to multiple cells

Cell arrays

set all cells to 'A'
s=cell(1,5);
s{:}='A'
ERROR: The right hand side of this assignment has too few values to satisfy the left hand side.

a) using the command deal  to expand 'A' to the number we need.
[s{:}]=deal('A')

b) converting string 'A' to a cell {'A'} that is mapped to all selected cells(:) of s
s(:)={'A'}
    'A'    'A'    'A'    'A'    'A'


Example: replace all 'C' with 'A'
s = {'C','B','C','B','C'};
idx = ismember(s,'C');
s(idx)={'A'}

    'A'    'B'    'A'    'B'    'A'

Struct array

set multiple fields of a struct array
[ s(10:20).field ] = deal( 'A' )

Example
% create struct array
for i=1:5
  Metadata(i) = struct('ID',i, 'group','A');
end
{ Metadata(:).group }
    'A'    'A'    'A'    'A'    'A'

a) using deal()
Metadata(2).group = 'B' ;
[ Metadata(3:end).group ] = deal( 'C' ) ;

b) using cell array to modify values
group = { Metadata(:).group }; % struct array to cell array
group(2)={'B'};
group(3:end)={'C'};
[ Metadata.group ]  = group{:}; % copy back to struct-array

% check values in struct-array
{ Metadata(:).group }
    'A'    'B'    'C'    'C'    'C'

see also:

Numerical matrices

set all values smaller than 0.5 to zero

x = rand(2,4)
    0.8641    0.4547    0.7844    0.9137
    0.3889    0.2467    0.8828    0.5583


idx = x<0.5

x(idx)=0
    0.8641         0    0.7844    0.9137
         0         0    0.8828    0.5583