Basu S
Basu S

Reputation: 51

Calculation between 2 vectors where one is 4d and other is 1d

I am using Matlab 2018b. One problem has emerged when I am working with 2 vectors. One is of 4d form and other is of 1d form. I would like to subtract the value of a vector from the values of the other vector.

Idea:

I need to run a loop upon the vector A and vector B. Inside the loop I'll obtain the value of the vector A and subtract a value of the corresponding index from B

But, I would like to solve the problem in a more MATLAB way rather than procedural way. Can you please guide me for this?

Example:

A=[val(:,:,1,1)
      = 0.67
    val(:,:,2,1)
        =0.55
   val(:,:,3,1)
        =0.12
   val(:,:,1,2)
      = 0.12
    val(:,:,2,2)
        =0.50
    val(:,:,3,2)
        =0.11
]
B=[1
    0]

The operation would be like this one

Result=[
            val(:,:,1,1) =0.67-1
            val(:,:,2,1) =0.55-1
            val(:,:,3,1) =0.12-1
            val(:,:,1,2) =0.12-0
            val(:,:,2,2) =0.5-0
            val(:,:,3,2) =0.11-0
]

thanks,

Upvotes: 0

Views: 169

Answers (1)

obchardon
obchardon

Reputation: 10790

In order to avoid using permute you can use two tricks:

  • Implicit expansion
  • Singleton dimension

If you want to substract a 1D matrix to a 4D matrix the problem is that matlab doesn't know on which dimension the substraction should be applied.

But matlab allows you to create a matrix with singleton dimension for example a matrix 1x1x1x2 can be created.

Here is an example:

% Creation of the 4D matrix
A = rand(3,4,5,2);
% Creation of another 4D matrix but with 3 singleton dimension
B = [1,0];
B = reshape(B,1,1,1,2);
%                   ↑
%              4th dimension

%Now matlab know that the substraction should be applied on the 4th dimension.
X = A-B;

Another example:

% Creation of the 4D matrix
A = rand(3,4,2,5);
% Creation of another 4D matrix but with 2 singleton dimension
B = [1,0];
B = reshape(B,1,1,2); %could also be written reshape(B,1,1,2,1)
%                 ↑
%             3th dimension

%Now matlab know that the substraction should be applied on the 3th dimension.
X = A-B;

Upvotes: 1

Related Questions