'num2str' Error
Mostra commenti meno recenti
Trying to have this result
Details- name:Tara Wilkins, ID:12344567, address:123 Happy Drv
Having errors when using num2str for the ID part, what am I doing wrong?
students(i) = struct();
students(1).ID = 12344567;
students(1).name = 'Tara Wilkins';
students(1).address = '123 Happy Drv';
students(2).ID = 15432123;
students(2).name = 'Fred Bloggs';
students(2).address = '125 Happy Drv';
students(3).ID = 34765765;
students(3).name = 'Jo Tamry';
students(3).address = '321 Happy Drv';
for i = 1:length(students)
disp(['Details- name:' ,students(i).name, 'ID:',students(i).[num2str(ID)], ', address:' ,students(i).address])
end
*Bolded the part that is the issue*
Risposta accettata
Più risposte (1)
Steven Lord
il 15 Ago 2019
Since you're using release R2019a, rather than using char array concatenation or sprintf I would append strings together.
students(1).ID = 12344567;
students(1).name = 'Tara Wilkins';
students(1).address = '123 Happy Drv';
S = "Details - name: " + students(1).name + ...
" ID: " + students(1).ID + ...
" address: " + students(1).address
MATLAB will automatically convert the number 12344567 to the text data "12344567" when appending it to the rest of the string S. The ellipses aren't necessary, but I wanted to avoid a long line of code since it would add scroll bars to my message.
Though if your format isn't constrained (which it probably is, since this sounds like a homework assignment) I'd probably break name, ID, and address onto separate lines for readability.
S = "Details" + newline + "Name: " + students(1).name + newline + ...
"ID: " + students(1).ID + newline + ...
"address: " + students(1).address
and maybe indent the fields by one or two tab stops or a couple spaces.
tab = sprintf('\t');
S = "Details" + newline + ...
tab + "Name: " + students(1).name + newline + ...
tab + "ID: " + students(1).ID + newline + ...
tab + "address: " + students(1).address
spaces = blanks(7);
S2 = "Details" + newline + ...
spaces + "Name: " + students(1).name + newline + ...
spaces + "ID: " + students(1).ID + newline + ...
spaces + "address: " + students(1).address
1 Commento
Guillaume
il 15 Ago 2019
It might just be me, but I find it a lot easier to picture what the output will look like with
S = sprintf('Details- name: %s, ID: %d, address: %s\n', bunchofvariables) %or "" for string output
than with:
S = "Details - name: " + students(1).name + ...
" ID: " + students(1).ID + ...
" address: " + students(1).address
which is cluttered by variable names in the midst of the text.
The newline and tab add even more clutter compared to:
S = sprintf('Details\n\tname: %s\tID: %d\taddress: %s\n', bunchofvariables) %or "" for string output
Categorie
Scopri di più su Startup and Shutdown in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!