How to make each element in a matrix into its own, separate matrix.
Show older comments
Currently trying to write a sudoku solver, except I want to make each already-given number into its own matrix filled by only that number. Is there a way to do this?
4 Comments
the cyclist
on 18 May 2015
This isn't clear to me, and I expect it won't be to others. Remember that the only thing we know about your problem is what you tell us. You might also want to give a numerical example of what you mean.
per isakson
on 18 May 2015
Guillaume
on 18 May 2015
Answers (2)
Walter Roberson
on 18 May 2015
T = importdata('easy.txt');
bigmat = mat2cell(T,ones(1,size(T,1)),ones(1,size(T,2));
1 Comment
Guillaume
on 18 May 2015
bigmat = num2cell(T);
num2cell is simpler than mat2cell for this.
You can easily import the whole matrix at once using textscan:
fmt = repmat('%f',1,9);
fid = fopen('easy.txt','rt');
A = cell2mat(textscan(fid,fmt,'MultipledelimsAsOne',true));
fclose(fid);
Which produces the following numeric matrix:
>> A
A =
7 9 0 0 0 0 3 0 0
0 0 0 0 0 6 9 0 0
8 0 0 0 3 0 0 7 6
0 0 0 0 0 5 0 0 2
0 0 5 4 1 8 7 0 0
4 0 0 7 0 0 0 0 0
6 1 0 0 9 0 0 0 8
0 0 2 3 0 0 0 0 0
0 0 9 0 0 0 0 5 4
If you then want to split this into individual 3x3 matrices, then one way would be to use mat2cell:
>> mat2cell(A,[3,3,3],[3,3,3])
ans =
[3x3 double] [3x3 double] [3x3 double]
[3x3 double] [3x3 double] [3x3 double]
[3x3 double] [3x3 double] [3x3 double]
Note that there is likely no point in splitting a numeric array into a cell array of 1x1 matrices, as in this case it would be much more efficient simply to keep the original numeric array intact. It all depends on what you are going to do with the data... however if you really want to do this, then use num2cell.
1 Comment
Guillaume
on 18 May 2015
I suspect that Anna wants to use a cell array so she can store all the possible values of an unsolved clue within the same cell.
Otherwise, yes, using a cell array is very pointless.
Categories
Find more on Characters and Strings 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!