您可以實現一些複雜的面向對象編程,但爲了簡單起見,我建議將所有不同類型的座標存儲爲結構,它們都具有成員type
以及該特定類型座標所需的任何其他成員。
然後,您可以定義所有轉換函數做單步驟都具有相同的函數簽名function out_coord = A2B(in_coord)
,如:
function cart = sphere2cart(sphere)
assert(strcmp(sphere.type, 'sphere')) % make sure input is correct type
cart.type = 'cart';
cart.x = sphere.R * sin(sphere.theta) * cos(sphere.omega);
cart.y = sphere.R * sin(sphere.theta) * sin(sphere.omega);
cart.z = sphere.R * cos(sphere.theta);
這些功能可以通過一個通用的convert
函數被調用是這樣的:
function output_coord = convert(input_coord, target_type)
output_coord = input_coord;
while ~strcmp(output_coord.type, target_type)
func = get_next_conversion_func(input_coord.type, target_type);
output_coord = func(output_coord);
end
它一次完成一個轉換步驟,直到output_coord
具有正確的類型。然後,唯一缺失的步驟是根據當前類型和目標類型確定下一步要執行的轉換的函數。在你的情況下,一個'線性'轉換鏈,這並不難。在更復雜的情況下,類型在複雜圖形中連接時,這可能需要一些最短路徑算法。不幸的是,這是一個有點麻煩Matlab中實現,但是一個硬編碼的解決方案可能是這樣的:
function func = get_next_conversion_func(current_type. target_type);
switch current_type
case 'A'
func = @A2B;
case 'B'
switch target_type
case 'A'
func = @B2A;
case {'C','D','E'}
func = @B2C;
end
case 'C'
switch target_type
case {'A','B'}
func = @C2B;
case {'D','E'}
func = @C2D;
end
...
end
可以肯定,有實現這個更聰明的方法,這基本上是在說,一個調度表根據當前類型和目標類型確定哪個方向。
編輯
繼喬納斯操作的方式從一箇中央類型的所有轉換的建議(比方說C
),所有這一切都可以簡化爲
function output_coord = convert(input_coord, target_type)
output_coord = input_coord;
if strcmp(output_coord.type, target_type)
return % nothing to convert
end
if ~strcmp(output_coord.type, 'C')
switch output_coord.type
case 'A'
output_coord = A2C(output_coord)
case 'B'
output_coord = B2C(output_coord)
case 'D'
output_coord = D2C(output_coord)
case 'E'
output_coord = E2C(output_coord)
end
end
assert(strcmp(output_coord.type, 'C'))
if ~strcmp(output_coord.type, target_type)
switch target_type
case 'A'
output_coord = C2A(output_coord)
case 'B'
output_coord = C2B(output_coord)
case 'D'
output_coord = C2D(output_coord)
case 'E'
output_coord = C2E(output_coord)
end
end
您可能想在您的第一個開關/箱體塊中使用input_coord – Jonas
我首先執行'output_coord = intput_coord',但是這肯定會被清理一下。代碼未經測試... –
這正是我想要的! 我喜歡你給出的原始解決方案,並認爲這是我正在尋找的。 但是用@喬納斯的建議,這允許更少的函數明確定義,並使其更好。 謝謝你們! 我更喜歡用Java和Python進行編碼,所以我很想了解更多關於這個問題。我看着調度表,這可能是我在找的東西。想知道這是否是正確的術語,所以我可以自己閱讀它? – Kaj