當輸入陣列大小不同時,我如何使用cellfun(或適當的替代方法)并獲得所有結果組合(即,評估陣列的交叉連接)?
這個例子使用了一個虛擬函式;實際函式更復雜,所以我正在尋找呼叫自定義函式的答案。使用 Matlab R2018a,所以我正在尋找與之兼容的答案。
a = 0:0.1:0.3; b = 100:5:120;
test = cellfun(@(x,y) myfunc(x,y,0), num2cell(a), num2cell(b));
function [result] = myfunc(i, j, k)
% k is needed as fixed adjustment in "real life function"
result = 0.1 * i sqrt(j) k;
end
上面的代碼回傳以下錯誤:
Error using cellfun
All of the input arguments must be of the same size and shape.
Previous inputs had size 4 in dimension 2. Input #3 has size 5
此示例的預期輸出是下面的“結果”列;為方便起見,顯示了 i 和 j。
| 一世 | j | 結果 |
|---|---|---|
| 0 | 100 | 10 |
| 0.1 | 100 | 10.01 |
| 0.2 | 100 | 10.02 |
| 0.3 | 100 | 10.03 |
| 0 | 105 | 10.24695077 |
| 0.1 | 105 | 10.25695077 |
| 0.2 | 105 | 10.26695077 |
| 0.3 | 105 | 10.27695077 |
| 0 | 110 | 10.48808848 |
| ETC | ETC | ETC |
uj5u.com熱心網友回復:
這里的答案是bsxfun。下面是一個作業示例。
% You need a function with the correct number of inputs.
% With your sample, I would do something like this.
myfunc = @(i,j,k) 0.1 * i sqrt(j) k;
myfunc_inner = @(i,j) myfunc(i,j,0);
% Side not: using separate files for functions is more
% efficient, but makes for worse examples on stackoverflow
%Setting up the inputs
a = 0:0.1:0.3;
b = 100:5:120;
%bsxfun, for two inputs, is called like this.
c = bsxfun(myfunc_inner, a', b)
bsxfun執行以下操作:
- 擴展輸入的標量維度,使其匹配
- 使用提供的函式 input 執行輸入的元素組合
在這種情況下,結果是:
c =
10 10.247 10.488 10.724 10.954
10.01 10.257 10.498 10.734 10.964
10.02 10.267 10.508 10.744 10.974
10.03 10.277 10.518 10.754 10.984
要以您請求的形式獲取輸入,只需運行c(:).
歷史注釋:
回到以前,我們不得不bsxfun更頻繁地使用。現在,當我們對數字執行簡單的操作時,Matlab 會在不通知的情況下擴展單個維度。例如,我以前經常使用以下樣式:
a = [1 2 3];
b = [4 5 6];
c = bsxfun(@plus, a', b)
而現在我們只寫:
c = a' b
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/519534.html
標籤:matlab
上一篇:Python通道器
