How to index a char array in order to use in strcat

114 visualizzazioni (ultimi 30 giorni)
I'm a beginner trying to write a function (in Octave) to concatenate element by element a cell array of strings and a numerical matrix. I use cell2mat to convert chordLetters, a cell array of strings, to a normal matrix and num2str to convert octave [I apologize for the confusing variable name, but from here on octave is a variable name of a matrix, not the programming language] , a matrix, to a char array. Finally I use a nested loop to go element by element and try to use strcat to concatenate each element of chordLetters with the cooresponding element in octave.
My function only worked correctly for certain cells, but other cells it did not concatenate. Upon trying to diagnose the problem I realized that indexing does not work the way I thought it would (again I'm a beginner). Let's say octave = [4,4,4,5; 3,2,2,2; 2,4,4,3] and test = num2str(octave), which displays what looks like the same matrix except now the class is char.
When I try to access the element test(3,2) it says "ans = ", instead of "4" which I want. How would I access this element of test without having to search for index of that number? Or if this is not possible using a char array, how would I concatenate element by element my original chordLetters with octave? I've read that sprintf is good for concatenation but I have absolutely no idea how to implement any of the printf functions (if someone would point me to a source where I can understand these functions I would be greatly appreciative, as the standard documentation in the octave manual is too complicated for me to understand).

Risposta accettata

Star Strider
Star Strider il 3 Gen 2019
The num2str call inserts spaces between the numbers (in MATLAB, and I assume also in Octave):
octave = [4,4,4,5; 3,2,2,2; 2,4,4,3];
test = num2str(octave)
Q = test(3,2)
producing:
test =
3×10 char array
'4 4 4 5'
'3 2 2 2'
'2 4 4 3'
so the character in that position is a space.
Use a format descriptor with num2str, and it works as you want it to:
test = num2str(octave,'%g')
Q = test(3,2)
producing:
test =
3×4 char array
'4445'
'3222'
'2443'
Q =
'4'
  4 Commenti
aweller3
aweller3 il 3 Gen 2019
It works perfectly, thanks again! From what I understand, '%g' formats it as floating point number with no spaces.
Star Strider
Star Strider il 3 Gen 2019
As always, my pleasure!
Correct. There are several other format options you can experiment with. I chose '%g' because it appears to be the most useful here.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by