簡體   English   中英

遍歷三個數組,將函數應用於元素並將輸出存儲在矩陣中

[英]Loop through three arrays, apply function to elements and store the outputs in a matrix

我想遍歷3個數組的不同元素,並根據它們的值創建一個矩陣。

如下所示,我的a向量的范圍是1到5,我的b向量的范圍是1到5,我的x向量的范圍是2到10。 然后對於來自ab特定值,使用等式y=a*x+b ,我想要得到的y向量對應於y矩陣的第一列向量中存儲的x值。

之后,一一更改ab ,我希望將不同y的結果存儲在y矩陣的相應列中。 我該如何實現呢?


這是我嘗試的代碼:

function mathstrial
    a = [1:1:5];
    b = [1:1:5];
    x = [2:2:10];    
    for e1 = a
        for e2 = b
            for e3 = x
                y = e1*x+e2;
            end
        end
    end
    disp(y)
end

我希望結果是

y =
3   4   5   6   7  ..
5   6   7   8   9  ..
7   8   9   10  11 ..
9   10  11  12  13 ..
11  12  13  14  15 ..
...

您可以做到這一點而無需任何循環-更具“ MATLAB風格”的處理方式。

% Your a and b, to get combinations as a 5x5 grid we use meshgrid
[a,b] = meshgrid(1:5, 1:5);
% We want to make a 5x5x5 3D matrix, where the 2D layers each use a different value
% for x, and the gridded a and b we just generated. Get the layered x:
x = repmat(reshape(2:2:10, 1, 1, []), 5, 5, 1);
% Now we want the corresponding layered a and b
a = repmat(a, 1, 1, 5); b = repmat(b, 1, 1, 5);
% Now calculate the result, ensuring we use element-wise multiplication .*
y = a.*x + b; 
% Reshape to be a 2D array, collapsing the 3rd dimension
y = reshape(y(:,:).', [], 5, 1);

所需結果:

y = 
[3,   4,   5,   6,   7
 5,   6,   7,   8,   9
 7,   8,   9,  10,   11
 9,   10,  11,  12,  13
 ...
 41,  42,  43,  44,  45
 51,  52,  53,  54,  55]

您可以通過使用size代替5s來輕松獲得合適的大小,從而使其更通用。

您可以在一個for loop建立y

a = [1:1:5];
b = [1:1:5];
x = [2:2:10];
y = zeros(5,5,5);
for ct = 1:length(a)
    y(:,:,ct) = (a(ct).*x)'+b;
end

b在第二維上,而a在第三維上。

甚至在一條不可讀的行中

y=repmat((a'.*x),[1,1,length(b)])+repmat(permute(b,[1,3,2]),[length(x),length(a),1])

a在所述第二,和b在第三維

a = [1:1:5];
b = [1:1:5];
x = [2:2:10];
y = zeros(5,5,5);
for i = 1:5
    for j = 1:5
        for k =1:5

            y(i,j,k) = i*x(k)+j

        end
    end
end
final_y = reshape(y, [5, 25])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM