如何在Matlab中轻松创建动态2D矢量矩阵

时间:2017-10-21 21:52:54

标签: matlab

鉴于我的代码:

G=zeros(height,width); %zeros or whatever

for y = 1 : height
    for x = 1 : width
         magnitude = sqrt(Gx(y,x)^2 + Gy(y,x)^2);
         gradient_direction = atan(Gy(y,x)/Gx(y,x));
         G(y,x) = [magnitude gradient_direction];
    end
end

我继续这样做(如果我不使用零()):

  

订阅的分配维度不匹配。

或者这个:

  

分配比非单身人士具有更多非单身人士rhs维度   标

2 个答案:

答案 0 :(得分:2)

虽然@atru的答案有效,但我想建议一种更快更整洁的矢量化方式,如果这样做有帮助的话。这里的操作可以很容易地转换为矢量化操作:

G=cat(3,hypot(Gy,Gx),atan(Gy./Gx));

答案 1 :(得分:1)

通过使用[<CLIMutable>] type Snippet = { title: string; tags: Collections.Generic.List<String> } [<CLIMutable>] type Item = { snippet : Snippet } [<CLIMutable>] type Response = { items : Collections.Generic.List<Item> } [<Test>] let ``Apply tags to videos`` () = let delimitedIds = ["id1";"id2";"id3"] |> String.concat "," let url = String.Format(requestTagsUrl, apiKey, delimitedIds) let response = httpClient.GetAsync(url) |> Async.AwaitTask |> Async.RunSynchronously if response.IsSuccessStatusCode then let root = response.Content.ReadAsAsync<Response>() |> Async.AwaitTask |> Async.RunSynchronously root.items.Count |> should equal 2 else Assert.Fail() ,您尝试将两个值分配给为索引为G(y,x,:) = [magnitude, gradient_direction];的单个值保留的点。解决此问题的一种方法是使用三维数组G,

(y,x)

现在,在每个点G(y,x),您可以存储这两个值,并在G=zeros(height,width,2); for y = 1 : height for x = 1 : width magnitude = sqrt(Gx(y,x)^2 + Gy(y,x)^2); gradient_direction = atan(Gy(y,x)/Gx(y,x)); G(y,x,:) = [magnitude, gradient_direction]; end end 位置G(1,2,1) magnitude处为(1,2)实例G(1,2,2)访问它们为gradient_direction。这假定GxGy都是大小高度为x宽的数组。

需要注意的重要一点是沿第三维的G切片也将是3D数组,即mag_dir = G(3,2,:)的大小为[1 1 2]而不是[1 2]。这可能会导致某些应用程序出错,例如包括尝试将mag_dir与另一个向量(没有额外维度)和线性代数运算连接起来。

要解决此问题,请使用reshape将维度明确更改为目标维度。对于这里的向量,它将是reshape(mag_dir, 1, 2)。对于像more_md = G(1,:,:)这样的2D切片也是如此 - 这需要实例more_md = reshape(more_md,2,5)

相关问题