How to add an element to an entire array?
6 views (last 30 days)
Show older comments
I'm looking to add an apostrophe to a 1x27 array, so that when it writes into an Excel file, it doesn't remove the leading zeros. Importantly, I am not attempting to add values to the array; my goal is to modify the values already present in the array to precede them all with an apostrophe. I have tried other methods to allow preceding zeros to remain, but none work, as the leading zeros are removed when I do anything else. Any advice is greatly appreciated.
0 Comments
Accepted Answer
Ayush
on 25 Jul 2023
Edited: Ayush
on 25 Jul 2023
One thing you can try is storing elements of array in form of string and then you can add apostrophe to them.Then when you want to use the numeric value, just remove the apostrophe and typecast the string back into the numeric value.
Hope it helps!
3 Comments
More Answers (1)
dpb
on 25 Jul 2023
You're going to have to illustrate what you want -- and best would be to provide a small sample code that illustrates the issue that folks here can run.
But, if the issue is how to display a numeric field in Excel with leading zeros, the answer is to use a custom numeric format. A format of "000000" will display integers in a zero-filled width of six and still treat the values as numeric.
If you turn them into text, you'll probaby rue having done so; Excel isn't very happy about text that looks like a number.
There's no way to "add" an apostophe to a numeric value in MATLAB, numbers are numbers and their internal storage is NOT what a visual representation looks like; you can do the same thing to convert the array to text with compose or num2str and then write the text representation, but that will have the same issues inside Excel itself.
Context on why it matters might help produce more/other answers...
2 Comments
dpb
on 25 Jul 2023
Edited: dpb
on 26 Jul 2023
"...because I do not know how to set one in Excel from within MATLAB, "
That would have to be done with the COM ActiveX server actxserver and the magic incantations to do so from the VBA equivalents. It's not terribly difficult overall, but can be extremely frustrating to work ones way through the arcane Excel doc's to actually make things work.
" the data being output to the file is binary, and the leading zeros are important for expressing the 8 bits "
Aha! Why didn't say so in the beginning! :)
a=randi(255,5,1)
t=strcat("'",dec2bin(a,8))
or, more general with using newer features
compose("'%s",dec2bin(a,8))
See Also
Categories
Find more on Data Import from MATLAB 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!