Store 3x3 matrix in a variable in a for loop - matlab

I have a 9x3 matrix that I subdivided into three (3) 3x3 matrix. Now I want to make a for loop function that will store each 3x3 matrix into a variable.
X=reshape(1:27,3,9)'; % sample 9x3 matrix
xx = mat2cell(X,[3,3,3],3); % subdivide X matrix into 3x3 cell matrix
for i:1:3
x(i) = xx{i,1}; %store the three cells into x1 x2 and x3 matrix
end
I know that this does not how it works in matlab but just to show the function I would like to attain.

You can use eval function.
X=reshape(1:27,3,9)'; % sample 9x3 matrix
xx = mat2cell(X,[3,3,3],3); % subdivide X matrix into 3x3 cell matrix
for i=1:3
eval(['x' num2str(i) ' = xx{' num2str(i) ',1};']);
end
But What you are asking for is not recommended at all. In fact i always avoid using eval because the code doesn't get checked by MATLAB editor.
It is also not a good idea to have multiple variables, instead use cells, structures, and so on for a better usage in the rest of your code.

Is this what you're looking for?
X=reshape(1:27,3,9)';
for i=1:3
block = X(3*i-2:3*i,:);
disp(block);
end

The preferred way to do this is to actually just store it in a 3D array and you can access each element along the third dimension. The reason for that is that MATLAB is optimized for computing using matrices, so if you keep all of your data in a matrix, operations can be performed in a vectorized fashion on all components.
Better yet you can remove the for loop needed to create it by using reshape and permute.
X = permute(reshape(X', [3 3 3]), [2 1 3]);
% And access each element
X(:,:,1)
X(:,:,2)
X(:,:,3)
This is going to be more performance than using cell arrays or eval.

Related

Are single loops or dense loops more computationlly efficent in matlab?

Im am currently writing a code to implement a numerical approximation to the 3D steady state heat equation using finite difference matrix methods. This involves discritising the 2nd order PDE into the matrix A and solving Ax=b. where x is temperature at each of the specified grid points. Further information on this type of question can be found here:
http://people.nas.nasa.gov/~pulliam/Classes/New_notes/Matrix_ODE.pdf
To complete this problem, I have represented the 3D matrix A by a 2D array calling the values in the 1D array b using an indexing function of the form:
i+(j-1)*Nx+Nx*Ny*(k-1)
for the (i,j,k)th element of the 3D matrix where Nx, Ny, Nz are the number of points in the x,y,z coordinates. There ends up being a lot of loop computation in order to create the matrix A and b and I was wondering what is the most computationally efficient and less memory exhaustive way to run these loops, i.e. is it better to use something like
for j=1:Ny
for i=2:Nx-1
b(i+(j-1)*Nx)=D4;
end
end
for j=1:Ny
for i=2:Nx-1
b(i+(j-1)*Nx+Nx*Ny*(Nz-1))=D3;
end
end
or should I condense these into a single loop like:
for j=1:Ny
for i=2:Nx-1
b(i+(j-1)*Nx)=D4;
b(i+(j-1)*Nx+Nx*Ny*(Nz-1))=D3;
end
end
I have preallocated both the arrays A and b. Is there a vectorised way to do this also?
Assuming Nx, Ny, Nz, D3 and D4 to be scalars and that you are using pre-allocation for b with zeros, you may try this vectorized approach -
I = 2:Nx-1; %// Vectors to represent i
J = 1:Ny; %// Vectors to represent j
ind1 = bsxfun(#plus,I,[(J-1)*Nx]'); %//' Indices, 1st set of nested loops
ind2 = bsxfun(#plus,I,[(J-1)*Nx+Nx*Ny*(Nz-1)]'); %//' Indices, 2nd set of loops
b(ind1) = D4; %// Assign values for 1st set
b(ind2) = D3; %// Assign values for 2nd set
The second method should be slightly faster since it performs the same number of calculations with fewer increments of the loop variables. You can look into MATLAB's built-in stopwatch commands tic and toc to time your code. http://www.mathworks.com/help/matlab/ref/tic.html
Something more vectorized might be possible but I would need to know more about the format of the arrays that contain D3 and D4. The reshape() function might be able to help.

Iterate over matrices in Octave

I need to perform the same operation on several matrices, so I'd like to write a for loop with, say, variable i where at each iteration, i has the value of one of my matrices.
Is that even possible in Octave?
For clarification: I do not want to iterate over elements of a matrix, but over a list of matrices.
You could have a 3d matrix, where each "layer" represent a 2d matrix, say:
A = rand(3,3,3);
for ii = 1:3
A(:, :, ii) %something
end
Or you could have cells, where each A{ii} is a 2d array, and you can use a loop in a normal way.
for ii = 1:3
A{ii} % something
end

create 3D (n:m:k) matrix in matlab using array 2D (i:3)

I need a 3D matrix in matlab, I have another 2D matrix (7570x3) too,
The 3D matrix should have zero number except of all dimensions in 2D matrix that should have 1 value. How can I do that.
i.e. 2D matrix (1,:) = 28,64,27 then 3d(27,64,27) should be 1
how can i do that?
Assuming a is your 2-d matrix, and b is the 3-d one, use sub2ind as follows:
b=false(max(a)); % preallocate memory for a logical zeros matrix b
b(sub2ind(size(b),a(:,1),a(:,2),a(:,3))) = 1;
Check to see what max(a) gives you to see if you can host a 3-d matrix of size(max(a) to begin with. Since you are interested in a logcial matrix (ones and zeros), the size of that matrix in memory is the same as the # of elements, n*m*l, so a 1000x1000x1000 will take 1 GB.
Note, it very well may be that b is very sparse, if that is the case you can refer to this thread to see how to deal with it. Know that at the moment, and to the best of my knowledge, matlab doesn't support 3d sparse matrices. So you may want to check this option from the FEX. When I think of it, you already have a sparse look-up table of the 3D matrix! it is just your 2D matrix you started with...
Thanks a lot #natan
for non-integer matrix also can use:
b=false(floor(max(a))); % preallocate memory for a logical zeros matrix b
b(sub2ind(size(b),floor(a(:,1)),floor(a(:,2)),floor(a(:,3)))) = 1;
or use round function:
b=false(round(max(a))); % preallocate memory for a logical zeros matrix b
b(sub2ind(size(b),round(a(:,1)),round(a(:,2)),round(a(:,3)))) = 1;

Cropping matrix

for examples, I have a 6x6 matrix, then I want to take out the small matrix which is located in the center of that matrix, say 2x2. Is there any smart way to do it ? Or I have to loop through the old matrix and then copying values to new one?
Thank you very much.
Of course you can. try for instance
A = rand(6,6); % // big matrix, an example
B = A(3:4,3:4); % // central sub matrix obtained using indices
which (in this case) is also equivalent to
B = A([3 4],[3 4]);
In general you can extract subvectors from a vector selecting the indices you are interested to.

Build a 3D least squares distance matrix without loops?

I am trying to build a three dimensional matrix out of three vectors where I take the least squares distance between each element of each vector as the entries of the matrix.
For example for the 3d matrix d,
d(m,n,o)=(vec1(m)-vec2(n))^2+(vec1(m)-vec3(o))^2+(vec2(n)-vec1(o))^2
I am currently doing this with a triple for loop:
d=zeros(N,M,O);
for o=1:O
for n=1:N
for m=1:M
d(n,m,o)=(((t(n)-r(m))^2)+((t(n)-z(o))^2)+((r(m)-z(o))^2));
end
end
end
My question is whether there is a quicker, cleverer way to do this for instance for a 2d version of this I could use:
%for n=1:N
% for m=1:M
% d(n,m)=(t(n)-r(m))^2;
% end
%end
d=(repmat(t(:),1,M)-repmat(r(:)',N,1)).^2; %this replaces the nested for loops from above Thanks Georg Schmitz
Whoever Georg Schmitz is came up with a way to use repmat to replace the double for loops in the 2d version. I could of course adapt this method and replace my triple for loops with one for loop that repeats the repmat method (o) number of times, But I feel like there should be a way to do this without loops.
Any ideas? Thanks
You can indeed vectorize the calculation:
%# properly reshape the vectors
vec1 = vec1(:); %# n-by-1
vec2 = reshape(vec2,1,[]); %# 1-by-m
vec3 = reshape(vec3,1,1,[]); %# 1-by-1-by-o
%# use bsxfun to efficiently replicate the arrays
d = bsxfun(#plus,bsxfun(#plus,...
bsxfun(#minus,vec1,vec2).^2,...
bsxfun(#minus,vec2,vec3).^2)),...
bsxfun(#minus,vec3,vec1).^2));
You should try pdist or pdist2 depending on your needs. pdist computes inner distances, while pdist2 computes a pairwise distance matrix.