Solving an array without for loops

6 ビュー (過去 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
  2 件のコメント
Lamont
Lamont 2024 年 3 月 6 日
Thank you so much for these examples.
Voss
Voss 2024 年 3 月 6 日
You're welcome!

サインインしてコメントする。


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
  1 件のコメント
Lamont
Lamont 2024 年 3 月 7 日
Thank you for your response.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by