Warm tip: This article is reproduced from serverfault.com, please click

Defining a matrix by avoiding the use of for loops

发布于 2020-11-27 22:59:09

I have a 3D matrix X of size a x b x c.

I want to create a 3D matrix Y in MATLAB as follows:

X = rand(10, 10, 5);
[a, b, c] = size(X);

for i = 1 : c
    for j = 1 : a
        for k = 1 : b

            if j<a && k<b
            Y(j, k, i) = X(j+1, k, i) + X(j, k+1, i).^4;
        
            else
            Y(j, k, i) = X(a, b, i) + X(a, b, i).^4;
            end

         end
    end
end

How can I do that by avoiding using a lot of for loops? In other words, how can I rewrite the above code in a faster way without using a lot of loops?

Questioner
Christina
Viewed
0
MichaelTr7 2020-11-28 23:58:11

Indexing Arrays/Matrices

Below I added a portion to your script that creates an array Z that is identical to array Y by using indexing that covers the equivalent indices and element-wise operations that are indicated by the dot . preceding the operation. Operations such as multiplication * and division / can be specified element-wise as .* and ./ respectively. Addition and subtraction act in the element-wise fashion and do not need the dot .. I also added an if-statement to check that the arrays are the same and that the for-loops and indexing methods give equivalent results. Indexing using end refers to the last index in the corresponding/respective dimension.

Snippet:

Y = zeros(a,b,c);
Y(1:end-1,1:end-1,:) = X(2:end,1:end-1,:) + X(1: end-1, 2:end,:).^4;
Y(end,1:end,:) = repmat(X(a,b,:) + X(a,b,:).^4,1,b,1);
Y(1:end,end,:) = repmat(X(a,b,:) + X(a,b,:).^4,a,1,1);

Full Script: Including Both Methods and Checking

X = rand(10, 10, 5);
[a, b, c] = size(X);

%Initialed for alternative result%
Z = zeros(a,b,c);

%Looping method%
for i = 1 : c
    for j = 1 : a
        for k = 1 : b
            if j < a && k < b
            Y(j, k, i) = X(j+1, k, i) + X(j, k+1, i).^4;
            
            else
            Y(j, k, i) =  X(a, b, i) + X(a, b, i).^4;
            end
         end
    end
end

%Indexing and element-wise method%
Z(1:end-1,1:end-1,:) = X(2:end,1:end-1,:) + X(1: end-1, 2:end,:).^4;
Z(end,1:end,:) = repmat(X(a,b,:) + X(a,b,:).^4,1,b,1);
Z(1:end,end,:) = repmat(X(a,b,:) + X(a,b,:).^4,a,1,1);

%Checking if results match%
if(Z == Y)
   fprintf("Matched result\n"); 
end

Ran using MATLAB R2019b