How can I add 'ones' until I get a length of 7 digits

4 ビュー (過去 30 日間)
Juan Rosado
Juan Rosado 2012 年 9 月 3 日
I have a vector consisting on < 1 x 3 double > that I would like to add ones until the seventh value is reached.
The variable input is this:
x = [1,2,3];
I want this vector:
x = 1 2 3 1 1 1 1 % length of 7
I can't type the 'ones' directly. I am looking for a code that automatically takes any vector of length less than 7 and add values of 'ones' until the seventh value is reached.
Can you please help?

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 3 日
result=ones(1,7);
result(1,1:length(x))=x

Image Analyst
Image Analyst 2012 年 9 月 3 日
編集済み: Image Analyst 2012 年 9 月 3 日
If you know for a fact that x is less than 7 long, and you want to stuff the new array back into x, you can do this:
x = [x, ones(1, 7 - length(x))];
The code below is more robust in that it will work for x's both less than 7 long, and longer than 7. If x is longer than 7 this crops the x so that the final array is only 7 long, but you could tack on the whole thing and get the longer array (full and complete x) if you wanted to by just eliminating the else block.
x = [1,2,3];
tempx = x;
lengthOfx = length(tempx)
x = ones(1, 7);
if lengthOfx <=7
x(1:lengthOfx) = tempx
else
x = tempx(1:7)
end

Star Strider
Star Strider 2012 年 9 月 3 日
My variations in terms of anonymous functions:
V7 = @(x) [x (length(x) < 7)*ones(1, 7-length(x))];
Vn = @(x,n) [x (length(x) < n)*ones(1, n-length(x))];

カテゴリ

Help Center および File ExchangeGet Started with Phased Array System Toolbox についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by