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

2 ビュー (過去 30 日間)
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.

採用された回答

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

その他の回答 (1 件)

Matt Tearle
Matt Tearle 2014 年 2 月 20 日
編集済み: Matt Tearle 2014 年 2 月 20 日
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by