Is it possible to fprintf/sprintf each row of elements in a vector using loop?

39 ビュー (過去 30 日間)
Daven Artajo
Daven Artajo 2021 年 11 月 26 日
編集済み: Daven Artajo 2021 年 11 月 26 日
I want to display the planets name and relative gravity such as: Moon gravity = 0.165 Earth gravity
One of the moderators recommended using a loop for this task. So, I'm trying to see if it's possible to write a code more effeciently using loops without having to print/display each planets one by one. Or is it not possible?
I've been playing around trying to find how to do it with no success, this is by far the closest I've gotten.
NOTE: the vectors are half than it is shown in the example
% Say for example
names = ["Earth"; "Venus"; "Mars"];
val = ["1.0000"; "0.8975"; '0.3915'];
planets = [names, val]
planets = 3×2 string array
"Earth" "1.0000" "Venus" "0.8975" "Mars" "0.3915"
% So I want to display the strings of each row together
% I created this loop that seems way too long
% When I used fprinf it ONLY shows the last row of strings without displaying -
% other rows
A = planets;
for B = 0:2
C = A(B + 1);
D = C';
E = append(C, " gravity = ");
F = [E(:,1)];
end
for G = 4:6
H = A(G);
I = append(H, " Earth gravity");
J = [I(:,1)];
end
fprintf('Grav. Acce.: ');
Grav. Acce.:
fprintf('%s ', F(:,1));
Mars gravity =
fprintf('%s \n', J(:,1));
0.3915 Earth gravity

採用された回答

Stephen23
Stephen23 2021 年 11 月 26 日
編集済み: Stephen23 2021 年 11 月 26 日
I would not use a loop:
N = ["Earth"; "Venus"; "Mars"];
V = ["1.0000"; "0.8975"; "0.3915"];
fprintf('%s %s Gravity\n', [V(:),N(:)].');
1.0000 Earth Gravity 0.8975 Venus Gravity 0.3915 Mars Gravity
  1 件のコメント
Daven Artajo
Daven Artajo 2021 年 11 月 26 日
編集済み: Daven Artajo 2021 年 11 月 26 日
OMG! Thank you very much. I used up way too much of my time creating a long unnecessary loop system. This was way simplier. I learned another way to use fprintf too. Cheers mate :)
I changed it up a bit to print how I needed it:
N = ["Earth"; "Venus"; "Mars"];
V = ["1.0000"; "0.8975"; '0.3915'];
fprintf('%s gravity = %s Earth gravity \n', [N(:), V(:)].');
Earth gravity = 1.0000 Earth gravity Venus gravity = 0.8975 Earth gravity Mars gravity = 0.3915 Earth gravity

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGraphics Performance についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by