Clear Filters
Clear Filters

Error using cell/unique (line 85) Cell array input must be a cell array of character vectors.

10 views (last 30 days)
i have created a cell to store [4x4] matrices. total matrices in a cell are 10. i want to find unique matrices of that cell and their occurrence.???
how can i do that in matlab. unique wont woks with a cell having matrix entries.

Answers (1)

BhaTTa
BhaTTa on 11 Jun 2024
To find unique matrices within a cell array and count their occurrences in MATLAB you can do it by converting each matrix to a string or a canonical form that can be compared, then using unique on these representations to find duplicates and count occurrences. Here's a step-by-step approach:
Step 1: Convert Matrices to Strings
One way to compare matrices is to convert them into strings. You can use the mat2str function for this purpose.
% Example cell array of matrices
cellOfMatrices = {
[1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12; 13, 14, 15, 16],
[1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12; 13, 14, 15, 16], % Duplicate
[4, 3, 2, 1; 8, 7, 6, 5; 12, 11, 10, 9; 16, 15, 14, 13],
randi(100, 4, 4), % Random matrices
randi(100, 4, 4),
[4, 3, 2, 1; 8, 7, 6, 5; 12, 11, 10, 9; 16, 15, 14, 13], % Duplicate
randi(100, 4, 4),
randi(100, 4, 4),
randi(100, 4, 4),
randi(100, 4, 4)
};
% Convert each matrix in the cell to a string representation
stringMatrices = cellfun(@mat2str, cellOfMatrices, 'UniformOutput', false);
Step 2: Find Unique Strings and Their Occurrences
Once you have the string representations, you can use the unique function along with the hist or accumarray functions to find unique matrices and their occurrences.
[uniqueStr, ~, ic] = unique(stringMatrices);
occurrences = accumarray(ic, 1);
% Display results
for i = 1:length(uniqueStr)
fprintf('Matrix:\n');
disp(uniqueStr{i});
fprintf('Occurrences: %d\n\n', occurrences(i));
end

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!