You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Matlab查找表函数,改用主对角线与反对角线计算?

Modified MATLAB Lookup Function for Diagonals

Got it, let's tweak your existing lookup function to use Y1's main diagonal and Y2's anti-diagonal instead of fixed rows/columns. Here's the revised code and breakdown:

Revised Function Code

function [x1,x2] = lookup_tab(y1,y2,X1,X2,Y1,Y2)
    % Extract main diagonal elements from Y1
    y1_main_diag = diag(Y1);
    % Find index of element closest to y1 (min absolute difference)
    [~, m] = min(abs(y1_main_diag - y1));
    
    % Extract anti-diagonal elements from Y2: flip columns first, then take main diagonal
    y2_anti_diag = diag(flip(Y2, 2));
    % Find index of element closest to y2 (min absolute difference)
    [~, n] = min(abs(y2_anti_diag - y2));
    
    % Retrieve scalar values from X1 and X2 using the calculated indices
    x1 = X1(n,m);
    x2 = X2(n,m);
end

Key Changes Explained

Let's walk through how this differs from your original code:

  • Replacing fixed row/column with diagonals:

    • For Y1: Instead of targeting a specific row with Y1(row,:), we use diag(Y1) to grab all elements where the row index equals the column index (the main diagonal).
    • For Y2: To get the anti-diagonal (elements where row index + column index = matrix size + 1), we first flip Y2 horizontally with flip(Y2, 2), then extract the main diagonal of the flipped matrix—this gives us the original Y2's anti-diagonal elements.
  • Index compatibility:

    • The index m returned by min() for Y1's diagonal directly maps to the column (and row) index of the closest element in Y1, matching how m was used as a column index in your original code.
    • The index n returned for Y2's anti-diagonal maps to the row index of the closest element in the original Y2 matrix, just like n was used as a row index originally.
  • Handling non-square matrices (optional):
    If Y1 or Y2 aren't square, diag() will extract the longest possible diagonal starting from the top-left corner. If you need to explicitly handle non-square cases for the anti-diagonal, you can replace the anti-diagonal extraction line with this more explicit version:

    % Get indices for Y2's anti-diagonal (works for non-square matrices)
    diag_length = min(size(Y2));
    row_indices = 1:diag_length;
    col_indices = size(Y2,2):-1:size(Y2,2)-diag_length+1;
    y2_anti_diag = Y2(sub2ind(size(Y2), row_indices, col_indices));
    

内容的提问来源于stack exchange,提问作者Shika93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:20:39