create vectors associated with each entry of an array and save them in a new matrix

1 view (last 30 days)
Say i have a matrix like A=[1 2; 3 4], and that i need to create 4, vectors each one associated to one entrance of the matrix, such that the first one goes from -1..1, and second from -2..2, and so forth. Wath i try was
for j=1:2
for k=1:2
W=linspace(-A(j,k),A(j,k),4)
end
end
the problem with that line is that it not save the data. Also i need that to create a new matrix, such that every row be one of the vectors that i mentioned.

Accepted Answer

David Young
David Young on 20 Feb 2014
Try
W(2*(j-1)+k, :) = linspace(-A(j,k),A(j,k),4)

More Answers (1)

Matt Tearle
Matt Tearle on 20 Feb 2014
Edited: Matt Tearle on 20 Feb 2014
The easy, brute-force way is just to append the new return from linspace to W each time. Start with W as an empty array:
A=[1 2; 3 4];
W = [];
for j=1:2
for k=1:2
W = [W;linspace(-A(j,k),A(j,k),4)];
end
end
If you're doing this with A large, growing an array like this is not very nice, so instead
A=[1 2; 3 4];
n = size(A,1);
W = zeros(n^2);
for j=1:n
for k=1:n
W((j-1)*n+k,:) = linspace(-A(j,k),A(j,k),n^2);
end
end

Categories

Find more on Creating and Concatenating Matrices 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!