Replace multiple matrix in a cell array based on condition

1 view (last 30 days)
need a help in replacing matrix in cell array
if i have cell array and matrix like this
A = {[1,1,2; 2,2,3];[1,3,4; 9,6,8];[1,7,8; 2,3,4];[1,1,4; 8,6,5]};
B = [2,2,2; 3,3,3];
when A has a value more than 5, it should be replace with B
then, the result have to be like this
result = {[1,1,2; 2,2,3];[2,2,2; 3,3,3];[2,2,2; 3,3,3];[2,2,2; 3,3,3]};
i have tried this, but it still gives me an error
rep = cellfun(@(c) any(any(c>5)), A, 'UniformOutput', true);
A{rep} = B;
Expected one output from a curly brace or dot indexing expression, but there were 2 results.
Any idea ?
Thanks in advance..

Accepted Answer

Stephen23
Stephen23 on 5 Feb 2020
Edited: Stephen23 on 5 Feb 2020
You were almost there, just one small change is required:
To assign to an unknown number of LHS elements the RHS must be scalar. In your case you want to assign cells themselves so the simplest is to make the RHS one scalar cell (not a non-scalar numeric).
>> idx = cellfun(@(c) any(c(:)>5), A); % default UniformOutput = True
>> A(idx) = {B}; % unknown number of cells = scalar cell
>> A{:}
ans =
1 1 2
2 2 3
ans =
2 2 2
3 3 3
ans =
2 2 2
3 3 3
ans =
2 2 2
3 3 3
  1 Comment
Song JL
Song JL on 5 Feb 2020
perfectly works !!
so, its just changing the curly bracket to B and put round bracket to cellfun variable..
Thank you so much..

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!