MATLAB Answers

creating a temporary matrix and then appending it to the original matrix

1 view (last 30 days)
Sparsh Garg
Sparsh Garg on 3 Aug 2021
Commented: Rik on 3 Aug 2021
So in python we can create a temp list/numpy array and then later on append it to the results
for example:
A is a NxN zeros matrix(A=zeros(4,2))
then i have something like this
for i=1:size(A,1)-1
temp_matrix=zeros(2,2)
do some processing to fill temp_matrix
now i want something along this
assign temp_matrix to the first and second row of A
then clear temp_matrix and whn i becomes 2
I again create temp_matrix and this time I assign it to the 3rd and 4th row of A
so if A is like this
[0 0
0 0
0 0
0 0]
and temp matrix is
[1 2
2 3] for first iteration
then at the end of first iteration
A should be
[1 2
2 3
0 0
0 0]
and then at next iteration when i becomes 2
temp_matrix is set to 0 again we process it to get a new result
and then we fill A so as to get
[1 2
2 3
new_val new_val
new_val new_val]
My current code tends to overwrite A(2,1) A(2,2) values so I decided to come up with this
Some info about what my code does
we have an image and we divide it into several 2x2 regions,now for those regions we are calculating the gradients(i.e we calculate the differenc between (pixel value at (2,2),(1,2),(1,1),(2,1) and (3,1) in anti clockwise manner.
grad1.mat is the result obtained by running the code mentioned in current code;grad_hard_code is the correct result when we consider 3 windows starting from pixel value (2,2)
Current code
grad1=zeros(4,2);
for i=1:size(grad1,1)-1
temp_grad=zeros(2,2);
varx=A{i,1};
vary=A{i+1,1};
grad1(i,1)=int32(varx(2,2))-int32(varx(1,1));
grad1(i,2)=int32(varx(2,2))-int32(varx(1,2));
grad1(i+1,1)=int32(varx(2,2))-int32(varx(2,1));
grad1(i+1,2)=int32(varx(2,2))-int32(vary(1,1));
end
Hard code
Subregions=load('Vsubsections.mat');
A=Subregions.A;
var1=A{1,1};
%disp(size(var1));
var2=A{2,1};
var3=A{3,1};
var4=A{4,1};
grad=zeros(6,2);
grad(1,1)=int32(var1(2,2))-int32(var1(1,1));
grad(1,2)=int32(var1(2,2))-int32(var1(1,2));
grad(2,1)=int32(var1(2,2))-int32(var1(2,1));
grad(2,2)=int32(var1(2,2))-int32(var2(1,1));
grad(3,1)=int32(var2(2,2))-int32(var2(1,1));
grad(3,2)=int32(var2(2,2))-int32(var2(1,2));
grad(4,1)=int32(var2(2,2))-int32(var2(2,1));
grad(4,2)=int32(var2(2,2))-int32(var3(1,1));
grad(5,1)=int32(var3(2,2))-int32(var2(2,1));
grad(5,2)=int32(var3(2,2))-int32(var2(2,2));
grad(6,1)=int32(var3(2,2))-int32(var3(1,1));
grad(6,2)=int32(var3(2,2))-int32(var4(1,1));
I have also included the Vsubsections.mat file which includes the pixel values for all the cellls.Please refer to the following code,
I have made some changes to store the windows and pixel values
  1 Comment
Rik
Rik on 3 Aug 2021
The step size in your unformatted code is 1, instead of 2. It looks like that would be the main edit required.

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!