Addpath with user defined string problem

2 次查看(过去 30 天)
Hey everyone,
Tried searching for answer but could not just figure it out. The problem is that matlab functions are on a shared platform. I'm trying to create addpath command that works with every user and the problem is that the path is different on every user. I don't understand why the following command doesn't work:
---------------------------------------------------------------------------------------------------------
username = char(java.lang.System.getProperty('user.name'));
%Returns the unique username that is different on each user and also used in the path, something like xxx123,also tried using username = getenv('username');
addpath(genpath((sprintf('C:\\Users\\%username\\xxxxx\\xxx\\xx',username))))
%This doesn't work, tried without genpath and with couple of different methods like using (['C:... but nothing worked.
%fprintf returns a weird 700 characters long string, something like 'C:\\Users\\50sername\\xxxxx\\xxx\\xx' 'C:\\Users\\79sername\\xxxxx\\xxx\\xx'...
---------------------------------------------------------------------------------------------------------
All help appreciated to how to use addpath and genpath with user defined variable!
Thank you!
  2 个评论
Adam
Adam 2017-1-3
编辑:Adam 2017-1-3
Well, I don't know about the whole thing and it's first day back at work after 2 weeks so I am maybe still slow on the uptake, but at the very least:
%username
is not a valid format specifier for sprintf. You should just be using %s if you want to substitute in a string which is what you seem to want to do. If you are trying to access an environment variable or something like that then certainly that wouldn't work in sprintf like that.
%u
expects an unsigned integer to be substituted in and the remainder 'sername' will just be inserted as a static string as you see in your output.
Valkmi
Valkmi 2017-1-3
Oh, works with %s. Thank you! Should have read sprint doc.

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2017-1-3
As per Adam's comment, your format string is wrong.
sprintf('C:\\Users\\%s\\xxxxx\\xxx\\xx', username)
is the correct form. Please see the documentation of format strings.
The reason you get a weird 700 character output is that your format string asks sprintf to interpret the variable content as unsigned integer (%u). For a string, that's the unicode values of the character (e.g. the string 'Valkmi' is [86 87 108 107 109 105]). When given an array of numbers, sprintf just replicate the format string until all numbers are consumed, hence you'd get: 'C:\\Users\\86sername\\xxxxx\\xxx\\xxC:\\Users\\87sername\\xxxxx\\xxx\\xxC:\\Users\\108sername\\xxxxx\\xxx\\xx...'

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Search Path 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by