Evaluate string as input keyword in matlab - matlab

How to evaluate a string which could be changed dynamically in code? for example:
A=rand(60, 60);
RangeC='10:end,:';
B=A(RangeC);
I know this is quite easy for others, but I have struggled for hours! Thanks in advance!

You can use the eval function but I would suggest to seperate RangeC in two variables like the example below. Also end won't be able to be evaluated so you can use size instead.
A=rand(60, 60);
RangeC1='10:size(A,1)';
RangeC2='1:size(A,2)';
B=A(eval(RangeC1), eval(RangeC2));

Related

How to optimize this string replacement code

I have an algorithm whose intermediate step is to replace a substring with another substring. To be precise I have a string HBIN_NEW and I have another string P. I want to replace every 6th,7th,8th element of the string HREP with the 1st,2nd,3rd element of PBIN_NEW. For this i have written the code
For example If PBIN_NEW='1111111101010101' and HBIN_NEW='1111100010101010'
then the new string HREP
should be HREP='1111111110101101'
for k=1:8:262144*8
HREP=strrep(HBIN_NEW,HBIN_NEW(k+5:k+7),PBIN_NEW(k:k+2));
end
Is this code correct to implement the above idea. And if yes, it is taking a long time do this replacement scheme, can somebody suggest some optimized way of doing this.
The wording on the question is still a bit awkward, and I'm not exactly sure how to get the example HREP given the wording, but most likely strrep is overkill for what it sounds like you are trying to do. A simple loop with assignments would be fine:
HREP = HBIN_NEW;
for k=1:8:length(HBIN_NEW)
HREP(k+5:k+7) = PBIN_NEW(k:k+2);
end
Often times though it can be better to just enumerate the position assignments and avoid the loop. So instead you have something like this:
HREP = HBIN_NEW;
HREP(6:8:end) = PBIN_NEW(1:8:end);
HREP(7:8:end) = PBIN_NEW(2:8:end);
HREP(8:8:end) = PBIN_NEW(3:8:end);
I think that does what you want, or should get you close enough ...
Finally, a bit of unsolicited style advice. Although Matlab doesn't have a very strict code style guide, most likely the use of all caps with underscores is not the best way of naming your variables. I personally prefer lowercase with underscores, e.g. pbin_new and only use capitalized words for constants ...

Checking existence of a input argument to a Matlab function

I'm trying to check the input of a Matlab function to see whether the user has forgotten about it or not (which is easy to do in this case).
If the user has not supplied number_obs then I want to pause the program and wait for the user to input this information.
Some other StackOverflow posts seem to suggest using ~exist however this doesn't seem to work. Can anybody suggest what I'm doing wrong here?
function output=test(number_obs)
if ~exist('number_obs'),
number_obs=input('How many observations do you have in your experiments?')
end
The Python equivalent would be something like:
def test(number_obs):
if nummber_obs != None:
output=raw_input('How many observations do you have in your experiments? :')
return output
You can do this with nargin
function output=test(number_obs)
if nargin<1
number_obs=input('How many observations do you have in your experiments?')
end
(Edited to correct the truth) It may not matter here, but to be on the safe side, you should always specify the type of object you're checking. In your case, its a 'var', so
if ~exist('number_obs','var'),
Thanks to dasdingonesin for pointing this out.

Passing multiple inputs into a MATLAB function via loop?

I have multiple variables var_1, var_2, var_3....var_9 (they are named like that) that I want to pass in a function. All of the variables are saved in the workspace. The function takes 2 variables, and spits out an output. I want to compare var_1 with all the variables, including itself, so I prefer to automate it in a loop.
So I want to execute
function(var_1,var_1)--> display answer, function(var_1,var_2)--> display answer...function(var_1,var_9)-->display answer all at once in a loop. I've tried the following, with no luck:
for i=1:7
functionname(var_1,var_'num2str(i)')
end
Where did I go wrong?
You cannot make a dynamic variable name directly. But you can use the eval-function to evaluate an expression as a string. The string can be generated with sprintf and replaces %d with your value.
for i=1:7
eval(sprintf('functionname(var_1,var_%d)', i));
end
But: Whenever you can, you should avoid using the eval function. A much better solution is to use a cell array for this purpose. In the documentation of Matlab there is a whole article about the why and possible alternatives. To make it short, here is the code that uses a cell array:
arr = {val_1, val_2, val_3, val_4, val_5, val_6, val_7, val_8, val_9};
for i = 1:length(arr)
functionname(arr{1},arr{i})
end

convert an array of string values to use as a formulas

I am new to coding and objective C so thanks for the help in advance.
I have a .plist file containing an array of strings filled with formulas such as
*5.3
/2
-10.5
I am able to retrieve these string values from the .plist file but I am getting a little stuck trying to append these string formulas to existing variables with the hopes of returning a converted number. For example I would like to use my variable 7 with the formula *5.3 and return 37.1
7 *5.3 -> 37.1
Any help would be greatly appreciated
Appending the string to a variable is straightforward; it can be accomplished with something like this:
NSString *equation = [NSString stringWithFormat:#"%d%#", variable, plistEntry];
You'll run into problems when you want to evaluate this equation, however. This SO question discusses expression evaluation in Objective-C. Dave DeLong's answer links to a couple of libraries that you may want to look into: DDMathParser and GCMathParser.
This can't be done as-is. You'll need one of the many free expression evaluators (probably in C) that float around on the web.
See this SO question.

Execute a "prepared" math operation in Objective-C

I want to to math operations with some kind of prepared formula that would look like tan(%f)*1000 or %f+%f where the %f has to be replaced by an argument.
Is there a function in Objective-C that I can pass the format of my formula and the required numbers to execute this prepared operation?
I hope the problem is described understandable, if not, leave a comment.
Thanks in advance.
Edit 1: Thanks for your answers so far, but I'm looking for something more dynamic. The block and inline function is great, but to static. I also understand that this may be something hard to achieve out of the box.
You may be interested in DDMathParser, found here. I believe it will do everything you're looking for.
There is nothing that would do it this way, however what you could do is rewrite your "format" into a function, and just pass the arguments it needs to have, much faster and much easier.
inline float add(float p_x,float p_y)
{ return p_x+p_y; }
inline is a compiler feature that you can use to speed things up. It will replace the function call with the code it executes when you compile. This will result in a lager binary though.
If I understand your question correctly, Objective-C Blocks are great for this.
typedef double (^CalcBlock)(double);
CalcBlock myBlock = ^(double input) {
return (tan(input) * 1000);
};
NSLog(#"Result: %f", myBlock(M_PI_2));
You can pass the block that contains your algorithm to other objects or methods.