How do I store the values of a for loop in a matrix array?
조회 수: 2 (최근 30일)
이전 댓글 표시
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/647910/image.png)
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
답변 (1개)
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
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)
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!