Clear Filters
Clear Filters

can I conduce this command?

3 views (last 30 days)
omri dagan
omri dagan on 9 Jun 2023
Answered: Shishir Reddy on 14 Jun 2023
hello, I'm tring to save this string, but the format is the same and it seems weird to write the command like that...
x_1 = sprintf('%.*fcos(%.*ft+%.*f)+%.*fcos(%.*ft+%.*f)',presi,X(1),presi,w_n(1),presi,phi(1),presi,X(2),presi,w_n(2),presi,phi(2));
x_2 = sprintf('%.*fcos(%.*ft+%.*f)+%.*fcos(%.*ft+%.*f)',presi,X(1)*r(1),presi,w_n(1),presi,phi(1),presi,X(2)*r(2),presi,w_n(2),presi,phi(2));
there is a batter way to get this output?
The image below is markout of the output strings, beside the 'cos','t','(/)' the all is numbers thet I whold like that the user of the overall function will be able to determine with the variable pressi.
thank you
and sorry for my English 😚

Answers (1)

Shishir Reddy
Shishir Reddy on 14 Jun 2023
Hi dagan,
As per my understanding, you want to improve the syntax of the command and make it more readable.
sprintf can be useful for formatting strings with variable values, but it may seem cumbersome in this case. So, you can directly concatenate the string expressions using string concatenation (+ operator) in MATLAB as shown below.
x_1 = num2str(X(1)) + "cos(" + num2str(w_n(1)) + "t+" + num2str(phi(1)) + ") + " + num2str(X(2)) + "cos(" + num2str(w_n(2)) + "t+" + num2str(phi(2)) + ")";
x_2 = num2str(X(1)*r(1)) + "cos(" + num2str(w_n(1)) + "t+" + num2str(phi(1)) + ") + " + num2str(X(2)*r(2)) + "cos(" + num2str(w_n(2)) + "t+" + num2str(phi(2)) + ")";
This approach directly combines the values and strings using the + operator, eliminating the need for sprintf.
The num2str function is used to convert numeric values to strings.
Both approaches will produce the same result, but using string concatenation might be more readable and straightforward in this case.
For further reference, please refer these links to know more about ‘String concatenation’ and ‘num2str’
I hope this helps resolving the issue.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!