Hi.
I have this line of code:
address = num2str(str2double(string(dec2bin(find(strcmp(dictionary,content(1:end-1)))))),'%04d');
It works, but I would like that the 4 is taken from a variable.
In particular, my variable is
numBits = ceil(log2(length(phrases)));
Is there a way to do so? Thanks

 채택된 답변

Les Beckham
Les Beckham 2022년 4월 14일
편집: Les Beckham 2022년 4월 14일

1 개 추천

You can also use %*d, like this
for k = 1:5
fprintf('%*d\n', k, 2*k); % the first argument (k) is the field width, 2*k is the value to print
end
2 4 6 8 10
Documentation is here
By the way, why are you converting to string and then to double and then back to a string?

댓글 수: 5

Star Strider
Star Strider 2022년 4월 14일
I’d forgotten about the variable filed width as an optional argument.
+1
Rosario Frontino
Rosario Frontino 2022년 4월 14일
편집: Rosario Frontino 2022년 4월 14일
Thanks for your answer, I'm still working on the code so I'll optimize that conversion.
I don't get how to implement your solution on my code since num2str has only two parameters (format being the second) and of course I can't use a third.
Use sprintf instead of num2str
for k = 1:5
sprintf('%*d', k, 2*k)
end
ans = '2'
ans = ' 4'
ans = ' 6'
ans = ' 8'
ans = ' 10'
.
Les Beckham
Les Beckham 2022년 4월 14일
편집: Les Beckham 2022년 4월 14일
You are welcome. @Star Strider is correct, sprintf is the right way to go.
If an answer in the forum solves your problem, it is considered gracious to accept it. If not please add a comment to request additional clarification. Thanks.
Yeah it works by using sprintf. Thanks you both

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2021b

태그

질문:

2022년 4월 14일

댓글:

2022년 4월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by