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

如何更新CartesianIndex?矩阵后三列索引偏移修正求助

修正CartesianIndex的列索引偏移问题

问题原因

当你通过sol.x_assignment[:,4:6]提取子矩阵后,findall返回的是子矩阵内部的相对索引,所以列索引范围是1-3,对应原矩阵的4-6列,需要给列索引加上3的偏移量来得到原矩阵的绝对索引。

解决方案

方法1:利用CartesianIndex的加法特性(最简洁)

Julia中的CartesianIndex支持直接与另一个CartesianIndex做加法运算,直接给所有索引的列部分加上3:

index_left = findall(x -> x == 1, sol.x_assignment[:,4:6]) .+ CartesianIndex(0, 3)

方法2:手动提取并修改索引分量

通过提取每个CartesianIndex的行和列分量,给列分量加3后重新构造索引:

index_left = findall(x -> x == 1, sol.x_assignment[:,4:6])
index_left = [CartesianIndex(idx[1], idx[2]+3) for idx in index_left]

方法3:直接在原矩阵上筛选(避免子矩阵偏移)

跳过提取子矩阵的步骤,直接在原矩阵中找到值为1且列索引在4-6之间的元素:

index_left = filter(idx -> 4 ≤ idx[2] ≤ 6, findall(x -> x == 1, sol.x_assignment))

验证效果

处理后index_left的输出会符合你的预期:

CartesianIndex(2, 4)
CartesianIndex(3, 4)
CartesianIndex(10, 5)
CartesianIndex(11, 4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:01:10