Solving an array without for loops
조회 수: 2 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (2개)
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
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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!