How can I make a vector of constant value which length is 100 not using 'for&while'.
189 ビュー (過去 30 日間)
古いコメントを表示
How can I make a vector of constant value which length is 100 not using 'for&while'.
for example I want to make 'a'. a=[3 3 3 3 3 ........ 3 3 3 3]
0 件のコメント
採用された回答
per isakson
2013 年 7 月 30 日
編集済み: per isakson
2013 年 7 月 30 日
Try
a = 3 + zeros( 1, 100 );
and
a = repmat( 3, [1,100] );
0 件のコメント
その他の回答 (1 件)
Andrew Potvin
2023 年 8 月 1 日
編集済み: Andrew Potvin
2023 年 8 月 1 日
The above is NOT the approved MATLAB approach. It requires relatively slow floating point math (or repmat). Instead, do this:
a(1,1:100) = 3;
3 件のコメント
Andrew Potvin
2023 年 8 月 2 日
I'm curious what happens when you also try the following in your various MATLAB's:
function testD(k,sz)
D(1:sz(1),1:sz(2)) = k;
end
I'm guessing you'll find it's faster. If you really want to overkill this little experiment, perhaps log the total time of running each test 1000 times.
My original point was simply that
M(1:Nrows,1:Ncols) = c;
is the MATLAB-iest way to initialize a vector/matrix with a single constant value.
;-)
- AP
DGM
2023 年 8 月 4 日
編集済み: DGM
2023 年 8 月 4 日
This is what I get:
% in R2023a (forum):
% 0.49ms 0.27ms 3.8ms 0.93ms
% in R2019b:
% 2.1ms 0.34ms 12ms 5.1ms
% in R2015b:
% 2.1ms 0.55ms 17ms 8.2ms
% in R2009b:
% 4.6ms 3.4ms 12ms 9.8ms
Logging the total times would require modifying timeit() in a manner that defeats its existing functionality. Timeit() already does multiple calls and a bunch of work to eliminate the influence of cycle variation and overhead.
My hardware is a 13-year old 6-core AMD board that I got out of a dumpster. Take that with a grain of salt.
Mind you, none of these are really all that bad. The difference between 0.5ms and 5ms is probably negligible; I've just seen too many books full of old recommendations that I know need a big asterisk next to them.
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!