How do I store the values of a for loop in a matrix array?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Antworten (1)
Jan
am 9 Jun. 2021
Bearbeitet: Jan
am 9 Jun. 2021
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 Kommentare
Jan
am 11 Jun. 2021
Bearbeitet: Jan
am 11 Jun. 2021
@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)
m(:, :, 1, 2)
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
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!