How do I store the values of a for loop in a matrix array?

2 ビュー (過去 30 日間)
Goncalo Costa
Goncalo Costa 2021 年 6 月 9 日
コメント済み: Goncalo Costa 2021 年 6 月 11 日
I am in need to use a delta function and to preserve the output values into different matrix arrays.
I defined the delta function, , for a 64 x 64 matrix as:
function [d] = delta2(u, u0, v, v0)
d=0;
if u - u0 ==0 && v -v0 ==0
d=1;
end
The intention is for the programme to analyse every (u,v) point for a centre point (u0, v0). This means, to start at (u,v) = (0,0) and move throught the square image until finishing at (u,v) =(63,63). Once this is done, the programme should restart for a different (u0,v0) value until reaching (u0,v0) = (63,63).
The purpose is to obtain a different matrix of 0s and a single 1 for every (u0,v0) value.
My attempt so far was:
for u0 = 1:64
for v0 = 1:64
for u = 1:64
for v = 1:64
mat = delta2(u, u0, v, v0);
end
end
end
end
The problem is that the values obtained in the loop are not being stored, because the output for mat is always a single value of 1 or 0, and as stated above I wanted a matrix per (u0,v0) value.
How can I make the code run for every (u0,v0) value in order (I mean start at (0,0) , (0,1), .... and end up at (64,64))?
How do I store the results in a 64 x 64 matrix array?

回答 (1 件)

Jan
Jan 2021 年 6 月 9 日
編集済み: Jan 2021 年 6 月 9 日
One solution might be indexing the output
...
mat(u, u0, v, v0) = delta2(u, u0, v, v0);
...
But this can be simplified. At first the function delta():
function d = delta2(u, u0, v, v0)
d = double((u == u0) && (v == v0));
end
But the main loops can be omitted also:
v = 1:64;
m = (v == reshape(v, [1, 1, 1, 64]) & ...
v.' == reshape(v, [1, 1, 64]));
As side effect this needs 0.05 seconds on my computer (i5, Matlab R2018b) instead of 1.08 seconds of the original loop.
  5 件のコメント
Jan
Jan 2021 年 6 月 11 日
編集済み: Jan 2021 年 6 月 11 日
@Goncalo Costa: You do get a set of such matrices with my code:
v = 1:4;
m = (v == reshape(v, [1, 1, 1, 4]) & v.' == reshape(v, [1, 1, 4]));
% Test:
m(:, :, 1, 1)
ans = 4×4 logical array
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
m(:, :, 1, 2)
ans = 4×4 logical array
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
and so on. These matrices are stored in a 4D array efficiently. An alterative, which takes more RAM is to store them in a cell array:
n = 4; % Or 64, as you want
v = 1:n;
m = (v == reshape(v, [1, 1, 1, 4]) & v.' == reshape(v, [1, 1, 4]));
C = squeeze(num2cell(m, [1,2]));
C{1,1}
C{1,2} % Same as above
Goncalo Costa
Goncalo Costa 2021 年 6 月 11 日
Thank you, I will give this ago again, I struggled to understand you omitted the main loop and so I struggled to comprehend its use. I will give this a second go. Thank you so much.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by