필터 지우기
필터 지우기

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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by