Build Matrix from X and Y Coords and Corresponding Values
Show older comments
Hello,
I have three vectors and I want to construct a matrix from them.
- 'a' is a vector of length n, containing magnitude data.
- 't' is a vector (also length n) of time indices at which the samples in 'a' occur.
- 'f' is a vector (length m) of frequency indices at which the samples in 'a' occur.
t = 1:1:2500; % Vector of sample indices
f = 1:1:100; % Vector of frequency indices
a = rescale(square(t)); % Vector of magnitude values
How can I construct matrix 'M' with each value in 'a' occurring at the corresponding coordinate in (t, f), and all other indices in 'M' = 0?
- Using diag(a) does not work, because 't' and 'f' are of different lengths. I can resample or interpolate 'M' to change the resulting square matrix into a rectangular one, but this corrupts the data. I do not want to reduce the number of rows of M by decimation, but rather by allowing 'r' values of m to occupy each row.
% diag and resamp method - does not work.
M = diag(a);
% ratio of 't' to 'f'
r = length(t) / length(f);
% resample 'M' to dimensions of [length(f) x length(t)]
M_rect = resample(M, 1, r, 'Dimension', 2);
- I have tried simply writing element-by-element into 'M' in a for-loop, however for obvious reasons, this leaves me with a square matrix of either nxn. Essentially this is identical to diag(a).
% Single index Loop method - does not work
for i = 1:length(t)
M(i, i) = a(i);
end
- I have tried writing element-by-element into 'M' in two nested for-loops with row and column indices, however this results in 'M' having correct dimensions, but the values of 'a' fill every column. Essentially this is identical to diag(a).
% Dual index Loop method - does not work
for i = 1:length(t)
for j = 1:length(f)
M(j, i) = a(i);
end
end
This seems like it should be quite simple, but it's been wrecking my head. Any help would be most appreciated.
Thanks in advance,
Ben
1 Comment
Matt J
on 9 Nov 2022
What are the intended dimensions of M? How is it that "f is a vector (length m) of frequency indices at which the samples in 'a' occur" but length(f)~=length(a)?.
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!