Solving an array without for loops

2 次查看(过去 30 天)
Lamont
Lamont 2024-3-4
评论: Lamont 2024-3-7
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.

回答(2 个)

Voss
Voss 2024-3-4
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

the cyclist
the cyclist 2024-3-4
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by