douye6812 2014-05-16 03:34
浏览 78

用Struct指针方法处理矩阵数据成员

I am working on creating a struct that represents a Matrix with methods to manipulate the data within the type. There are two methods that I use as an example to set a single row or column to a specific value. Here is a snippet of my code:

type Matrix struct {
    Height, Width int
    data [][]int
}

func NewMatrix(nrows, ncols int) (mat *Matrix) {
    mat = new(Matrix)
    mat.Height = nrows
    mat.Width = ncols
    mat.data = make([][]int, nrows)
    for i := range mat.data {
        mat.data[i] = make([]int, ncols)
        for j := range mat.data[i]{
            mat.data[i][j] = 0
        }
    }
    return
}

func (mat *Matrix) SetCol(col, val int) {
    for i := 0; i < mat.Height; i++ {
        mat.data[i][col] = val
    }
}


func (mat *Matrix) SetRow(row, val int) {
    for i := 0; i < mat.Width; i++ {
        mat.data[row][i] = val
    }
}

When I use this Matrix type and manipulating the data attribute like so:

mat := NewMatrix(33,33)
mat.SetCol(2, 3)
mat.SetRow(2, 3)

I am finding that the data attribute of the Matrix instance is being set within the method SetCol but once it returns from this method the data appears to be the empty matrix that I initialized it to.

Why is the data attribute that I am manipulating in the method not persisting past the lifetime of the method call? How can I fix this?

Edit

I found out that the issue was that I was instantiating a new instance of a Matrix on each iteration in a loop which is why the matrix always appeared to be empty after I manipulated it with SetCol and SetRow. So the question is not really valid.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 这种微信登录授权 谁可以做啊
    • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
    • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
    • ¥15 网络设备配置与管理这个该怎么弄
    • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
    • ¥20 西门子S7-Graph,S7-300,梯形图
    • ¥50 用易语言http 访问不了网页
    • ¥50 safari浏览器fetch提交数据后数据丢失问题
    • ¥15 matlab不知道怎么改,求解答!!
    • ¥15 永磁直线电机的电流环pi调不出来