arrays - Assigning values to a sub-matrix of a indexed sub-matrix in Matlab -


i'm not sure if i've used correct wording in title describe problem. please feel free edit reflect description below.

suppose have sudoku solver program , lets input matrix following,

a = randi(10,[9,9])-1; 

i index 3x3 sub-matrices coulumnwise 1 9. let's variable nsubmat representing index can take values between 1 9.

i index submatrices in following way,

submat(nsubmat) = a((1:3)+(3*floor((nsubmat-1)/3)),(1:3)+(3*mod(nsubmat-1,3))); 

now, want access , modify value in (2x3) position of submat without having create submat in first place(say avoid unnecessary copies).

to elaborate, if have function submatrix() implement above, statement following,

submatrix(a((1:3)+(3*floor((nsubmat-1)/3)),(1:3)+(3*mod(nsubmat-1,3))),[2,3]) = 5; 

or even,

submatrix(a((1:3)+(3*floor((nsubmat-1)/3)),(1:3)+(3*mod(nsubmat-1,3))),[2:3,2:3]) = [1 2;3 4]; 

i know matlab interpreter automatically optimizes lhs=rhs type assignments speed, above matrix operation important more reasons(algorithimically) reducing copies , speeding code not dwell here. have seen required syntax in c++ library called armadillo, i'm not sure if same can done matlab.

you using simple linear indexing. following code self-explanatory.

matrixrows=9; matrixcols=9; blockrows=3; blockcols=3; accessrow=2; accesscol=3;  = randi(10,[matrixrows,matrixcols])-1; allpos=allcomb(accessrow:blockrows:matrixrows,accesscol:blockcols:matrixcols); linpos=sub2ind(size(a),allpos(:,1),allpos(:,2));  % access them usual , put value a(linpos)=-100; 

result:

a =   8     9     7     3     6     4     1     6     8  9     1     9     6     3     4     4     8     2  1     9     6     1     9     6     9     9     9  9     9     0     7     0     7     3     5     3  6     4     8     0     4     7     5     1     1  0     8     9     2     3     2     2     1     2  2     1     6     0     7     6     7     2     6  5     4     7     0     7     6     2     8     4  9     9     7     8     1     1     5     2     3 

after running above code:

a =   8     9     7     3     6     4     1     6     8  9     1  -100     6     3  -100     4     8  -100  1     9     6     1     9     6     9     9     9  9     9     0     7     0     7     3     5     3  6     4  -100     0     4  -100     5     1  -100  0     8     9     2     3     2     2     1     2  2     1     6     0     7     6     7     2     6  5     4  -100     0     7  -100     2     8  -100  9     9     7     8     1     1     5     2     3 

note: allcomb generates possible combinations of input arguments. can use this faster allcomb (according answer).


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -