How do i print a vector in matlab with also something before the values. For example i have a vector with the following values A' = [1 2 3]. I want to print it out in such a way that the output will be
w0 = 1
w1 = 2
w2 = 3
How do i do this?
Can i do this using a loop?
I am using the following code and i am not getting the right output
for qux = 1:3
fprintf('w%i=%.4lf\n',qux-1,answ);
end
Output:
w0=w1=w2
Your format string is not formed properly. Specifically '%.4lf' should be '%.4f'. Additionally, the third input to fprintf should be A(qux) to access the value in A.
for qux = 1:3
fprintf('w%i=%.4f\n', qux-1, A(qux));
end
I would, however, recommend using '%g' to use a format that optimizes the display of each number. Additionally, you could remove the for loop and do something like
A = [1, 2, 3];
fprintf('w%i = %g\n', [0:numel(A)-1; A])
If I have understand the question correctly, I think that you could do that with the following code:
for i = 1:3
disp(['w' num2str(A(i)-1) '=' num2str(A(i))]);
end
Using disp and num2str you could get the following output:
w0=1
w1=2
w2=3
Related
In Matlab some functions adapt their output to the number of output variables in the call. For example I can do:
A=[[1 2 3];[4 5 6]];
s=size(A);
And I get
s=[2, 3];
But if I want to handle independently width and height I can do:
[h, w]=size(A);
And I get:
h=2;
w=3;
Now, if I have a function that always output a vector of let's say 3 elements. Is there a way to assign each element to a different variable?
I mean to avoid an scenery like this:
pos=getPosition();
X=pos(1);
Y=pos(2);
Z=pos(3);
I hope I have explained what I mean.
I've had the same problem. Mostly with functions handling coordinates as in your example. My solution was to create the following function:
function varargout = dealOneByOne(vector)
% Assign each column of vector to each variable on the output variables
%
for i=1:size(vector,2)
varargout{i}=vector(:,i);
end
end
Then you can just do
[X,Y,Z]=dealOneByOne(getPosition());
I'm not aware of a simpler way to do it.
Let's define a test function as follows:
function x = test()
x = [1 2 3];
end
Given the function above, this is what I would normally perform in order to split the output array into many distinct variables:
out = num2cell(test());
[a,b,c] = deal(out{:});
A wrapper function can be defined in order to avoid spreading the above assignment into multiple lines:
[a,b,c] = vout_num(test());
function varargout = vout_num(x)
C = num2cell(x);
varargout = C(:).';
end
In your example, the wrapper function would be used as follows:
[X,Y,Z] = vout_num(getPosition());
Is there a way in matlab to force a function to output a certain number of arguments? For example this is what matlab does:
function [a,b,c] = practice
if nargout >=1
a =1;
end
if nargout >=2
b=2;
end
if nargout ==3
c = 3;
end
end
d(1:3) = practice()
% d = [1 1 1]
I would want:
d(1:3) = practice()
% d = [1 2 3]
Can I get this behavior without needing to say
[d(1),d(2),d(3)] = practice()
There is an option to let your function output everything when only a single output argument is used:
function varargout=nargoutdemo(x)
varargout{1}=1;
varargout{2}=2;
varargout{3}=3;
if nargout==1
varargout={[varargout{:}]};
end
end
For non uniform return data, it might be necessary to switch to a cell
If you wish not to change the function, you could use this a little bit more generic code:
out=cell(1,3)
[out{:}]=practice
Please not, that this returns a cell, not an array. That's because array to comma separated list conversion is not directly possible.
I am trying to write a function transform(A) which when given a matrix A returns a new matrix. The new matrix should be obtained according to following:
if A has more than one row then interchange the first and second row. After this square the elements in the first row.
So far thats what I have written:
function[Anew] = transform(A)
dimension = size(A);
if dimension(1) > 1 %if there is more than 1 row
A([1 2],:)=A([2 1],:);
end
A(1,:,:) = A(1,:,:).^2 %squares elements in the first row
end
I tested my function by invoking it in matlab.
I noticed that because i dont have a semi colon next to A(1,:,:) = A(1,:,:).^2
I still obtain the desired result but not as output of the function.
I obtain A =
instead of Anew =
If i put a semi colon next to A(1,:,:) = A(1,:,:).^2; then I dont get an output at all.
Could you tell me what is wrong and what should I change in my program to obtain output as Anew?
Thank you
To return a value from a function in Matlab, you must directly assign to it.
In your case, you need to assign to Anew at the end of the operation (you could also technically just use that variable all-together).
function [Output1, Output2] = SomeFunction( ... )
% Do Some Work
% Store Output
Output1 = Result1(:,2) %some output
Output2 = Result2(3:end, :) %some other result
end
function[Anew] = transform(A)
dimension = size(A);
Anew = A;
if dimension(1) > 1 %if there is more than 1 row
Anew ([1 2],:)=Anew([2 1],:);
end
Anew(1,:,:) = Anew(1,:,:).^2; %squares elements in the first row
end
Is there a way to define multiple variables efficiently in matlab? Everything I've found isn't quite what I'm looking for. Here's the situation:
parstrs = {'a','b','c'};
parvals = [1 2 3];
I want an efficient command which would in effect do the following;
parstrs = parvals;
where the result is that the number 1 is stored in the variable a, 2 is stored in b, and 3 is stored in c, etc.
I'm open to doing this with cells or structs.
Any suggestions?
More clarification: As I mention below, I would like to write code that doesn't care how long the list of variable names is for use in curve fitting. The best way I've discovered is to use a structure, like the following:
parstrs = {'a','b','c'};
parvals = num2cell([1 2 3]);
partmp = {parstrs{:};parvals{:}};
pars = struct(partmp{:});
The problem with this is that the pars structure can't be edited in the same way. That is,
pars = setfield(pars,partmp{:});
will throw the following error:
Error using setfield (line 48)
Inputs must be either cell arrays or strings.
You're looking for eval, but that would probably still require a loop (yes you could generate a lengthy command, but do you really want that?):
Loop (please do not use this!):
for ii=1:numel(parvals)
eval([parstrs(ii) '=parvals(' ii ')']);
end
eval is most of the time totally not needed and discouraged; changing to cells is much easier to manage and use. You already have the variables in a vector, what's the problem with just using indexing to inspect them?
You should explain your application a bit more, so we can understand what you're really after, why you really want to use this kind of variable assignment.
For exporting variables outside from a gui to the base matlab environment, you can switch to evalin, and use it as follows:
function main_gui()
% do your thing, generate some values
parvals = [1 2 3];
% now is the time to export
give_me_my_vars({'a','b','c'});
% note that the following function is nested:
function give_me_my_vars(parstrs)
for ii=1:numel(parvals)
evalin('base',[parstrs(ii) '=' parvals(ii)]);
end
end
end
This is only possible for simple scalars, which fit in a string. I think you actually want to look for something to switch variables from one workspace to another (gui to base), but I don't know if that'd be possible.
You could use
parstrs = {'a','b','c'};
parvals = {'1' '2' '3'};
cellfun(#(x,y)evalin('caller', [x '=' y]), parstrs, parvals)
Alternatively, you could do something like
parstrs = {'a','b','c'};
parvals = {1 2 3};
parstrs = cellfun(#(x)[x ','], parstrs, 'UniformOutput', false);
eval(['[' parstrs{:} '] = deal(parvals{:});'])
However, as MATLAB's code analyzer will already complain about, this is a bit smelly. Usually, mass-defining variables using eval and friends is a sign you should think about a different approach.
For example, why do you even want to be able to address the values by separate variable name? Why is parvals(1), parvals(2) etc. not good enough?
You can create a structure with field names from parstrs with values taken from parvals like so:
parstrs = {'a', 'b', 'c'};
parvals = [1 2 3];
nValues = length(parvals);
for iValue = 1:nValues
s.(parstrs{iValue}) = parvals(iValue);
end
The structure, s, then looks like this:
s =
a: 1
b: 2
c: 3
So instead of a = 1, you'd have s.a = 1, but I think it's otherwise what you were after.
You could do something like:
[a, b] = function_returning_values();
You can also use eval.
Most of the chances that you can store the values in a single array:
x = [1 2 3];
Then, instead of writing a , write x(1) , instead of b write x(2), etc...
How about something like [a,b,c] = deal(1,2,3)? Or am I oversimplifying?
If I have an input like [1 2 3; 4.0 c] and I want it to output it like 1234.0c in matlab. What function can I use ? I am looking for something like trim in php.
Any idea ?
Thanks
You can use this to remove any number of spaces from inside of a string:
>> a = char(' he llo wor ld ');
>> a(isspace(a)) = [] %replaces all of the space with nothing
a =
helloworld
You can use isstrprop function with approppriate categories. For your case,
>> str = '1 2 3; 4.0 c';
>> str(isstrprop(str, 'alphanum') | str == '.')
ans =
1234.0c
You can use functions like isletter, isnumeric, etc. if you like.
Besides, you can create your own function in one line as follows
>> myTrim = #(x)(x(isstrprop(x, 'alphanum') | x == '.'));
>> myTrim(str)
ans =
1234.0c
Note that you ask [1 2 3; 4.0 c] as an input which is not a proper syntax for MATLAB. I assumed you wanted to ask for a string. In addition, trim actually implies removing leading and trailing white space from a string and there is strtrim for this in MATLAB.
It is not a valid MATLAB argument.
But if you have something like
a = ['1', '2' ,'3'; '4', '.','c'];
you can use
a(:)'
to get
142.3c
or
a = a';
a(:)'
to get
123.4c