String values change when leaving method

I am unable to assign string values from one vector to another without what I believe to be pointer errors occuring.
The process:
I assign strings to a string vector:
fileName(k) = string(Filelist(k).name);
I then assign strings from within the string vector to parameters:
obj.channel(i).fileName = fileName(i);
The assignment works as expected, and the strings are all assigned correctly. Upon leaving the method, I print out the values of the strings to console and they a re all completely incorrect! The strings are all the same value and are assigned to the final string value of the string vector.
Instead of the string being:
A B C D E
The string is:
E E E E E
I have a suspicion this has to do with how Matlab assigns pointers and performs garbage cleanup when interacting with multiple scopes/classes. If anybody has a solution to this problem I would greatley appreciate it.

4 Comments

Can you show us a small (at most 20 lines) section of code with which you can reproduce this behavior? I want to try to eliminate the possibility that your code is doing something different than what you expect / believe it's doing before we start looking at those lower-level possibilities.
Code snippet from within the method:
for k=1:length(Filelist)
if ~strncmp(Filelist(k).name, '.', 1)
fileName(k) = string(Filelist(k).name);
end
end
for i = 1 : obj.channelCount
obj.channel(i).setFileName(fileName(i));
end
Code snippet from outside the method:
function names = getChannelNames(obj)
for i = 1 : obj.channelCount
names(i) = obj.channel(i).getFileName();
end
end
Code output:
names =
1×8 string array
"B" "B" "B" "B" "B" "B" "B" "B"
Hi Steven, I am wondering if you have had a chance to look into this issue, as I am still unable to figure it out.
Ethan, the line of codes in your question is different as compared to your comment. You are using custom get and set methods. Is obj.channel(i) an instance of your custom class? Can you show the definition of these get and set method? Preferably, can you share a small standalone example, with simple class definitions so that we can recreate the error?

Sign in to comment.

 Accepted Answer

The problem ended up being I had only allocated one memory location for the string, but pointed at it with multiple instances of different objects. I did not realize I had setup my code to do. This is why I had this problem.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!