2013-05-28 487 views

回答

1

我不知道你的輸入變量或你想要什麼類型的輸出的數據類型,所以這只是一個例子:

a = ones(1,20); % 20 input values 
fprintf('%d',a(1:min(numel(a),16))) 

>> 1111111111111111 

a = ones(1,10); % 10 input values 
fprintf('%d',a(1:min(numel(a),16))) 

>> 1111111111 

上面打印最多16個值和作品甚至如果輸入,a是空的。問題在於,如果您希望在輸入中的元素少於16個時打印默認值。在這種情況下,這裏有一種方法:

a = ones(1,10); % 10 input values 
default = 0; % Default value if numel(a) < 16 
fprintf('%d',[a(1:min(numel(a),16)) default(ones(1,max(16-numel(a),0)))]) 

>> 1111111111000000 

如果你有一個列向量,你必須調整它們。

編輯:

爲了應對@Schorsch提出了一個問題,如果不是裁剪數組中的元素與大於16倍的值,你希望他們能夠在下一行打印,可以做與此:

形式的
a = ones(1,20); % 20 input values 
default = 0; % Default value if numel(a) < 16 
fprintf('%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d\n',[a default(ones(1,16-mod(numel(a),16)))]) 

>> 1111111111111111 
    1111000000000000 

變體可以,當然,也可以代替前兩個解決辦法,我給的使用,但打印字符串可能難以閱讀。

+0

另一個問題是,如果有超過16個值做什麼。 @ ansam-qas是否希望他們被刪除?或換一個新的行? – Schorsch

+0

@Schorsch:這個問題還不清楚。請參閱我的編輯,它爲此案提供瞭解決方案。 – horchler

+0

+1似乎涵蓋了所有的基地現在 – Schorsch

0

爲什麼不使用顯式計數器,使fprintf中功能:

printIdx = 1; % Init the counter, so that after 16 iterations, there can be a linebreak 
% Run a loop which just print the iteration index 
for Idx = 42 : 100+randi(100,1); % Run the loop untill a random number of iterations 
    % ### Do something in your code ### 
    fprintf('%d ',Idx); % Here we just print the index 

    % If we made 16 iterations, we do a linebreak 
    if(~mod(printIdx,16)); 
     fprintf('\n'); 
    end; 
    printIdx = printIdx + 1; % Increment the counter for the print 
end 
0

如果你有興趣在每一行的末尾(無論長短)智能地創建一個換行符,您可以使用「 \ b「退格字符以刪除行末尾的行,然後是」\ n「以創建新行。下面的示例:

fprintf('%u, %u \n',magic(3)) %will end the output with "2, " 

fprintf('%u, %u \n',magic(4)) %will end the output with "1 {newline}" 

在這兩種情況下,發送2退格,然後換行會導致一個乾淨的行尾:

fprintf('\b\b\n') % in one case, will truncate the ", " and in the other truncates " \n" 
+0

更新:寫入ASCII文件時,Backspace字符不會總是工作。使用fseek(fid,-2,0)「備份」2個字符並開始重寫。 – Scott