Building a matrix in a faster way

9 ビュー (過去 30 日間)
Azza
Azza 2012 年 10 月 16 日
Hi,
I am trying to build a matrix by giving each array in the matrix the same value in its first column. The value is [0;0;1]. My code look something like this:
yv = 1:-1:-1;
xv = -1:1:1;
for Y = 1:length(yv)
for X = 1:length(xv)
M(:,1,X,Y) = [0;0;1];
end
end
I was wondering if there is more efficient way to give the arrays for length (yv) and (xv) the value [0;0;1] instantly without using the for loop. My matrix in original is much larger than this and I need to make the code as faster to execute the data as possible.
Highly appreciate any help with this.
Best wishes
AA

採用された回答

Matt J
Matt J 2012 年 10 月 16 日
d=[0;0;1];
M=d(:,1,ones(1,length(xv)), ones(1,length(yv)))
  2 件のコメント
Walter Roberson
Walter Roberson 2012 年 10 月 16 日
Which can also be written as
M = repmat(d, [1, 1, length(xv), length(yv)]);
Matt J
Matt J 2012 年 10 月 16 日
Yes, although repmat does use mcode containing loops, and therefore can be slow.

サインインしてコメントする。

その他の回答 (1 件)

Azza
Azza 2012 年 10 月 17 日
Many thanks Matt and Walter for your help. Both your answers are very valuable. The thing with my code is that I need to keep a counter in each line. For example the code with the for loop should look something like this:
for Y = 1:length(yv)
for X = 1:length(xv)
counter = 1;
M(:,counter,X,Y)= [0;0;1];
counter = counter;
M(:,counter,X,Y) = A*Rflip*M(:,1,X,Y)+B;
end
end
Thus, the counter should change from value 1 to 2 accordingly.
I have also replicated the matrix for A, Rflip and B in order to accomodate the M value for the length of arrays of (xv) and (yv) similar to your methods. The original sizes of matrices A and Rflip were 3*3 for each element. So I managed to replicate the matrix to [3 3 3 3] for (xy) and (xv) While for B was 3*1 and I made it into [3 1 3 3]. When I tried to execute the line with the replicated matrices for A, Rflip and B {while excluding the counter} I got this error message:
??? Error using ==> mtimes Input arguments must be 2-D.
So would you kindly help me in giving the length of arrays for (xv) and (xy) the same value of M without using the lengthy for loop method while including the counter?
Best wishes
AA
  1 件のコメント
Matt J
Matt J 2012 年 10 月 17 日
Perhaps. But first Accept-click the answer we gave you and then start a new post for your new question.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by