Solving an array without for loops

2 vues (au cours des 30 derniers jours)
Lamont
Lamont le 4 Mar 2024
Commenté : Lamont le 7 Mar 2024
I am trying to replace some "for-loops" in my code. I want to take a 3-D array (denoting X,Y, and Z) and turn the 3x1 array into a 3x'length' array where each column represents a new position. Once I generate an array with all my locations, I want to apply the array's values column by column. Again, I am NOT trying to use a "for-loop" for incrementing through each column of the "posittion array".
Another way to state this problem. I have two arrays,
Array_1= [3,length]
Array_2=[3, length_2]
I want to operate all of Array_2 with each column of Array_1.
The resulting array from the operation will be the same size as Array_1.

Réponses (2)

Voss
Voss le 4 Mar 2024
permute might be useful. Example:
Array_1 = rand(3,10); % size of Array_1: [3, 10]
Array_2 = rand(3,15); % size of Array_2: [3, 15]
temp_Array_1 = permute(Array_1,[1 3 2]); % size of temp_Array_1: [3, 1, 10]
temp_product = temp_Array_1.*Array_2; % size of temp_product: [3, 15, 10]
temp_sum = sum(temp_product,2); % size of temp_sum: [3, 1, 10]
result = permute(temp_sum,[1 3 2]); % size of result: [3, 10]
whos
Name Size Bytes Class Attributes Array_1 3x10 240 double Array_2 3x15 360 double cmdout 1x33 66 char result 3x10 240 double temp_Array_1 3x1x10 240 double temp_product 3x15x10 3600 double temp_sum 3x1x10 240 double
  2 commentaires
Lamont
Lamont le 6 Mar 2024
Thank you so much for these examples.
Voss
Voss le 6 Mar 2024
You're welcome!

Connectez-vous pour commenter.


the cyclist
the cyclist le 4 Mar 2024
Your question is stated abstractly enough that it is difficult to give specific advice (at least for me).
I think it is possible, though, that if you permute Array_2 so that length_2 extends into dimension 2, you might be able to do vectorized operations on Array_1 and Array_2, relying on implicit expansion.
Here is a trivial example:
rng default
% Input data
A = rand(3,7);
B = rand(3,5);
% Permute B to extend into 3rd dimension, instead of 2nd
B_p = permute(B,[1 3 2]);
% Perform an example operation that relies on implicit expansion
C = sum(A.*B_p,3);
% Show that C is now the size of original A
size(C)
ans = 1×2
3 7
  1 commentaire
Lamont
Lamont le 7 Mar 2024
Thank you for your response.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by