Info
This question is closed. Reopen it to edit or answer.
How to assign mutliple vectors to matrix diagonals
2 views (last 30 days)
Show older comments
I have 3 vectors that I want to assign as diagonals to a matrix. Vector A is the center diagonal, Vector B is above the center diagonal, Vector C is below the centre diagonal.
So my final matrix should have 3 diagonals.
Now, say that these vectors each have 3 separate columns (now a matrix), how would i go about producing 3 matrices that demonstrate the above? How can i do this? I have tried to use the gallery('tridiag',A,B,C,
B=ones(3,22);
M=zeros(23);
n=1; k=1;
for n=1:3;
for k=1:23
for g=1:22;
super_diag(n,g)=B(n,g);
diag(n,k)=-A(n,k); % -ve to make values -ve
sub_diag(n,g)=C(n,g);
end
M{n}=gallery('tridiag',sub_diag(n,g),diag(n,k),super_diag(1,g));
end
end
This does not seem to work, any ideas where I have gone wrong?
0 Comments
Answers (1)
Guillaume
on 18 Oct 2016
I have no idea what you're trying to do with your code, it makes no sense, from the comment about creating a sparse matrix followed by no sparse matrix creation, to cell indexing into a matrix, through the pointless copying of scalar values.
Trying to decode what you say, you have 3 matrices (not vectors), A, B and C with 3 columns each and you want to create 3 tridiagonal matrices from the corresponding columns of each. In which case:
A = [1:9; 11:19; 21:29]'; %demo data
B = [101:110; 111:120; 121:130]'; %demo data
C = [201:209; 211:219; 221:229]'; %demo data
assert(size(A, 2) == size(B, 2) && size(A, 2) == size(C, 2), 'A, B, and C must have the same number of columns');
assert(size(A, 1) == size(C, 1) && size(B, 1) == size(A, 1) + 1, 'A and C must have the same number of rows. B must have one more row');
m = arrayfun(@(colidx) gallery('tridiag', A(:, colidx), B(:, colidx), C(:, colidx)), 1:size(A, 2), 'UniformOutput', false)
2 Comments
Guillaume
on 18 Oct 2016
You're not going to get any more generic than what I've written. Notice that none of the sizes are hardcoded (unlike your loop solution). The code will work with A, B and C of any height as long as B is one element taller than A and C, and with any number of columns as long as A, B and C have the same number. It will generate as many matrices as there are columns.
This is ultra generic. I actually stated the only conditions required for the code to work in the two assert.
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!