How do I print the contents of a vector along with index labels?
9 views (last 30 days)
Show older comments
MathWorks Support Team
on 20 Aug 2019
Edited: MathWorks Support Team
on 3 Jan 2024
I want to index a vector of complex numbers so that the on-screen output looks like
1 1.0000 - 5.0000 i
2 -5.0000 + 3.0000 i
3 …. ….
and all I can manage on screen via a command such as [real([1:length(c)]'),c] is
ans =
1.0000e+00 + 0.0000e+00i 1.0000e+00 - 5.0000e+00i
2.0000e+00 + 0.0000e+00i -5.0000e+00 + 3.0000e+00i
How do I replace the first column of indices with integers while leaving the second column of complex numbers intact?
Accepted Answer
MathWorks Support Team
on 15 Nov 2023
Edited: MathWorks Support Team
on 3 Jan 2024
If 'c' is a vector of complex numbers, then 'c' has the data type 'double (complex)'. When 'c' is concatenated with the indices, the result takes the data type ‘double (complex)’. Arrays and vectors can only contain data of one type, so the argument real([1:n]') is converted to a complex number.
To display the values with indices, use the 'fprintf' function, which can display multiple values by passing multiple arguments or an array. Continuing with the example, the following code will display the index along with the value of the vector at that index up to 4 decimal places:
>> fprintf('%d %.4e + %.4ei\n', [(1:length(c)); real(c)'; imag(c)'])
Note that the 'fprintf' function will display results in column order (e.g. the values in rows 1, 2, and 3 in the first column will replace '%d', '%.4e', and '%.4e' respectively). Also note that there is no format specifier for complex numbers, so the real and imaginary parts of the numbers are in separate columns and displayed in scientific notation.
Please run the following command on MATLAB R2018a to know more about 'fprint' function:
web(fullfile(docroot, 'matlab/ref/fprintf.html'))
In particular, the 'formatSpec' argument will allow you to specify formatting options like the precision of the numbers.
When editing vectors, it is recommended to use the variable editor. In the Workspace pane of the MATLAB editor, double click a variable to open the variable editor. This will allow editing of the variable's contents as though it were a spreadsheet.
Please follow the below link to search for the required information regarding the current release:
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!