how to replace each element of a array with the row cell of another array in matlab

To replace each element of an array with the row cell of another array in MATLAB, we can use a loop or vectorization. Here's an example that uses indexing and loops:

main.m
% create two arrays
A = magic(4);
B = {'foo', 'bar', 'baz', 'qux'};

% loop over each element of A
for i = 1:numel(A)
    % get the row index for B
    row = ceil(i / size(A, 2));
    % replace the element of A with the corresponding row cell of B
    A(i) = B{row};
end
271 chars
12 lines

This code creates an array A and a cell array B. It then loops over each element of A, calculates the row index for B, and replaces the element of A with the corresponding row cell of B.

Here's an example that uses vectorization:

main.m
% create two arrays
A = magic(4);
B = {'foo', 'bar', 'baz', 'qux'};

% calculate row indices for B
rows = ceil((1:numel(A)) / size(A, 2));

% use indexing and cell indexing to replace elements of A with cells of B
A = reshape(B(rows), size(A));
245 chars
10 lines

This code calculates the row indices for B using vectorized calculations. It then uses indexing and cell indexing to reshape B into the same shape as A and replace the elements of A with the corresponding cells of B.

gistlibby LogSnag