Hauptinhalt
Results for
In a previous Q & A, Jan Simon pointed to Cody: Sum 1:2^n. The current leading solution to that problem has node-count (or more simply, "length") 10. Apparently, 10 is the minimal length (per the official length-function on File Exchange) of any function taking input & generating output:
function y = test_cody_solution(x)
y = x;
end
Per Cody instruction examples, additional computation within a function definition increases the solution length. For example, both of the following functions have length 12:
function y = test_cody_solution(x)
y = [x];
end
function y = test_cody_solution(x)
y = x+1;
end
My question is: what kinds of ninja-style coding idioms even exist in MATLAB which actually perform definite computation but at the same time do not increase the node-count above 10? I'm not able to imagine what could be going on in order for someone to solve a given non-trivial Cody puzzle in length 10 or 11? IOW, without respect to any particular Cody problem, could someone please give an example of a non-trivial function which somehow comes in at or just above the absolute lower bound? Any explanation of the magic would be appreciated as well.
Thanks, Brad
Some of Matlab's toolbox functions are affected by magic strings or magic numbers, which are strings or numbers with a deeper meaning besides the normal value. Both are considered as bad programming patters, because they provoke confusions, when the magic keys appear with the normal meaning by accident. See http://en.wikipedia.org/wiki/Anti-pattern
Example 1:
clear('myVariable')
clear('variables')
While the 1st clears the variable myVariable, the later clears all variables. Here 'variables' has a meta-meaning. The problem appears, when 'variables' is an existing variable:
a = 1;
variables = 2;
clear('variables')
disp(a) % >> 1
Only variables is cleared, which cannot be understood directly when its definition is 1000 lines before.
Example 2:
uicontrol('String', 'default')
This creates a button with the empty string '' instead of the expected 'default', because this is the magic string to invoke the default value get(0, 'DefaultUIControlString'). The same concerns properties of other graphic objects also, e.g. the 'name' property of figure or the string of uimenu. There is a workaround which allows the user to display 'default': Simply use '\default'. Unfortunately this is doubled magic, because in consequence it is impossible to display the string '\default'. Obviously a bad idea.
Example 3:
Graphic handles are doubles (although gobject of the new R2013a seems, like this is subject to changes? [EDITED: Yes, it changed with HG2 in R2014a]). But then a handle can be confused with data:
a = axes; % e.g. 0.0048828125
plot(a, 2, '+')
But you cannot draw the point [0.0048828125, 2] by this way, because the 1st input is considered as handle of the parent. Here all possible values of handles are magic. Collisions are very unlikely, but there is no way to avoid them reliably - as long as handles have the type double.
Question:
Which functions are concerned by magic values? What are the pitfalls and workarounds?
function b = most_change(a)
a(:,1)=a(:,1)*0.25;
a(:,2)=a(:,2)*0.1;
a(:,3)=a(:,3)*0.05;
a(:,4)=a(:,4)*0.01;
d=sum(a,2);
c=max(d);
for i=1:length(d)
if d(i)==c
b=i;
end
end
i got wa please explain idont understand
How do I can delete my account?
I am wondering what others use for those little short-cuts or niceties in MATLAB. I have in mind something you wrote or something somebody else wrote or an underused MW function.
Here are my two favorites.
This is a simple script I use. Here is the entire contents of CLC.m (yes, it is capitalized):
clear all,close all,clc
Very simple, but I use it all the time. Here is another one I use so often that I forget not every machine has it (though every machine should, IMO):
Here is an underused MW function that I occasionally employ when working on someone else's machine. The usual response is, "Wait, what did you just do?"
home
What are some of yours?
Given a tic tac toe board:
1 represents X
0 represents empty.
-1 represents O
It is X's move. If there is an immediate win possibility, choose a square for an immediate win. Otherwise return 0.
Return absolute index of the square of choice. If multiple square are valid, return them in order.
Example:
Input a = [ 1 0 1
-1 1 0
0 -1 -1]
Output wins is [4 8]
Can anyone explain it in detail?
I'm confused with the sentence I marked ans bold style.
Thanks a lot~~~
I've written a valid answer to the last Cody problem, but it is not even close to the best answer. I have no idea how they made this short answer. To unlock it I need to solve another Cody question, but there are none left... :(
Anybody know how to unlock the last question?
Hi,
i'm "solving" number 30 cody's problem.
I think to solve that whit sortrows function.
If I have a z vector:
j = sqrt(-1);
z = [-4 6 3+4*j 1+j 0];
my funtion is:
function z = complexSort(z)
z(2,:)=sqrt(real(z).^2+imag(z).^2);
z=sortrows(z',-2);
z=z(:,1);
end
End it return the result
z =
6.0000 6.0000
3.0000 - 4.0000i 5.0000
-4.0000 4.0000
1.0000 - 1.0000i 1.4142
0 0
The question is: why imagine part in input is positive e sortrows trasform it in negative?
best regards
Marco
As I'm becoming more and more familiar with MATLAB, I'm starting to fall in love with it. I was wondering what are the coolest things that you all know MATLAB can do? As for me so far, the auto-code generation into another language is the coolest thing.
It is not uncommon for students to be assigned questions which they are required to complete "without using any built-in functions". There is not a great deal that can be programmed in MATLAB without using any built-in functions, but a little can be done -- but what, exactly is possible?
What a "built-in function" is, exactly, is open to interpretation. In the below, I refer instead to "publicly visible routines". Keywords (see below) are not publicly visible routines (they are "statements" or components of statements.) Any documented operation or call that invokes a MATLAB-supplied .m or .p or mex file or built-in library to do its work is a publicly visible routines. If you can use documented methods override the normal meaning of a statement or expression in practice by supplying alternate code, then the code probably involves publicly visible routines. If the language design is such that you could use documented methods to override the normal meaning of a statement or expression in theory (such as the behavior of adding two double, the code for which is in practice bundled into an internal MATLAB library), then I would still consider that a call to a publicly visible routine.
A MATLAB-supplied routine that is not documented, which is used for internal MATLAB purposes, could perhaps be held not to be a publicly visible routine, but it certainly would still be a "built-in function".
I exclude from the list any routine which there is no direct way to access, and is only used for internal purposes, such as the memory allocation routines.
This is what I have come up with:
- the names defined as "keywords" do not in themselves involve function calls to publicly visible routines. These keywords currently include 'break', 'case', 'catch', 'classdef', 'continue', 'else', 'elseif', 'end', 'for', 'function', 'global', 'if', 'otherwise', 'parfor', 'persistent', 'return', 'spmd', 'switch', 'try', 'while'. There is no functional form of any of these: for example, one cannot use global(s) to declare the name contained in the variable "s" to be global. (However, you can define an "end" method; https://www.mathworks.com/help/matlab/matlab_oop/object-end-indexing.html )
- scalar numeric double precision real-valued constants are handled at parse time, including unary plus and unary minus in front of them
- scalar numeric double precision constants followed immediately by "i" or "j" create a complex-value constant at parse time, including unary plus and unary minus in front of them
- whether a complete complex constant with real and imaginary part is handled at parse time is unknown
- literal character vectors and string objects are handled at parse time
- in sufficiently new versions, int64() and uint64() around an integer constant is handled at parse time. This was a change from previous versions which handled it at run time (after the integer had been converted to double precision...)
- whether any other casts such as uint16() or logical() are now handled at parse time is unknown
- assignment of a compete variable (no indexing, no substructure references, etc.) to a plain variable (no indexing, no substructure references, etc.) does not involve any function calls to publicly visible routines (unless I have overlooked a case involving objects)
- "if" or "while" applied to a scalar logical constant or to a scalar logical variable does not involve any function calls to publicly visible routines. However, it is not known whether there is any method to construct a logical value without calling a MATLAB routine: "true" and "false" are MATLAB routines, not constants, and logical() of a numeric constant might be handled at run time
- "for" in which the range is named as a scalar constant or scalar variable do not involve any function calls to publicly visible routines; for example, "for K = 5"
- defining an anonymous function does not involve any function calls to publicly visible routines
I may have overlooked something due to shortage of chocolate in my bloodstream.
The language described above is not Turing complete, and is not "sufficiently powerful" for the purposes of the Church-Rosser Theorem of general-purpose computability. It is also not possible to do any arithmetic in it, as arithmetic must be reducible to the Peano Postulates, and those require at the very least the ability to compare a value for equality with 0, which in MATLAB would require a call to the MATLAB routine "eq".
We all know that MATLAB is probably the best software for engineering purposes, I think it's a little expensive unless you have it for free on your school or place you work, please share your opinion about MATLAB cost, including toolboxes, student versions... is it that expensive?
I think a lot about how to more effectively teach MATLAB, internally to new hires, but also through my blog.
How did you learn MATLAB, what knowledge of programming did you have coming into learning MATLAB? When did you learn it is important also as the resources available have expanded radically in the last 15 years.
Answers from new users who are just beginning down this path are of particular interest, as those are who we can help the most.
Don't be shy, what was your matlab learning curve, how many years or months, what were the difficulties to begin with.
I think that the answers would be most valuable for new users, maybe you can also tell us the tricks that allowed you to master some parts or all matlab.
Now it's your turn...
Which Matlab related forums and newsgroups do you use beside MATLAB Answers? Which languages do they use? Which advantages and unique features do they have?
Do you think that these forums complement or compete against MathWorks and its communication platform?
Actually all answers are accepted.
O.k., admit it. Who has done this (or something that resulted in the same loss of info) before?
>> laster
??? Undefined function or variable 'laster'.
>> lasterr
ans =
Undefined function or variable 'laster'.
D'Oh! I need a ERRORBEFORELASTERR function.
What's one of your dumb MATLAB mistakes?
Are there parts of MATLAB that could disappear as far as you were concerned, things you don't need or which were "bad ideas" or which cause more trouble than they are worth in your experience?
One suggestion per answer please, so we can see how other people feel about the same matters.
I use MATLAB most days (when I'm at work!). It makes my life easier, for many reasons, which is why I like it.
What are the reasons you like it (assuming you do), and why?
I love MATLAB. It is so quick and easy to write software to do what you want. It has excellent debugging and profiling tools. It is cross platform, making code easy to share (assuming the other people have forked out for the not-so-cheap license). It has interfaces to other software.
However, there are some things about it that irk me. I'd like to hear from other people what things annoy them about MATLAB.
---------------------------------
Because this thread has become so large it is slow to load and navigate. Please post new answers in the second thread.
---------------------------------
As asked by Vieniava in "How to make a list of user's reputation?", some of us came up with interesting ideas on how to fill an updated list with the reputation scores of the contributors to Answers.
I took the initiative to compile a public list of users with meta info:
- position (desc ordering by reputation)
- id
- nickname (truncated to fit the page)
- reputation
- # of comments
- # of questions asked
- % accept rate
- # of posts answered
- # of accepted answers
The code used to compile the list is available at the bottom.
EDIT
TMW team implemented a page with the metascores: http://www.mathworks.com/matlabcentral/answers/contributors
Please refer to it and congrats to the team!
Use this function to retrieve info from the link above:
function [metainfo, elapsedTime] = metainfo(type,order)
% METAINFO - Retrieve metainfo on contributors to www.matworks.com/.../answers
%
% METAINFO Retrieve data sorted by reputation in descending order
%
% METAINFO(TYPE,ORDER) Specify TYPE and sorting ORDER as
% type : 'reputation'
% 'questions'
% 'answered'
% 'accepted'
%
% order: 'asc'
% 'desc'
%
% Examples:
%
% % Standard call (rep, disc)
% info = metainfo;
%
% % Sort by question answered in descending order
% info = metainfo('an','d');
%
% See also: URLREAD, REGEXP
% Author: Oleg Komarov (oleg.komarov@hotmail.it)
% Tested on R14SP3 (7.1) and on R2009b. In-between compatibility is assumed.
% 28 feb 2011 - Created
tic
% Check # inputs
error(nargchk(0,2,nargin))
% Retrieve inputs
if nargin == 0
type = 'reputation';
order = 'desc';
end
if ~exist(type,'var')
sortTypes = {'reputation','questions','answered','accepted'};
type = sortTypes{strncmp(type,sortTypes,numel(type))};
order = 'desc';
end
if ~exist(order,'var')
orderTypes = {'asc','desc'};
type = orderTypes{strncmp(order,orderTypes,numel(order))};
end
% Build url string
url = ['http://www.mathworks.com/matlabcentral/answers/contributors?'...
'dir=' order '&sort=' type '&page='];
% First read
[page, ok] = urlread([url '1']);
% Catch number of pages to read
if ok
totcon = regexp(page,'>1 - 50 of (\d+)','tokens');
totcon = dataread('string',totcon{1}{1},'%d');
nPages = ceil(totcon/50);
else
error('Cannot read ".../contributors?page=1"')
end
% Loop over contributors pages
metainfo = cell(totcon,7);
metainfo(1:end,1) = num2cell(1:size(metainfo,1));
for p = 1:nPages
if ok
endpos = 50*p;
% Id, Rep
expr = '><a href="\/matlabcentral\/answers\/contributors\/(\d+)';
data = regexp(page, expr,'tokens');
if 50*p > totcon; endpos = 50*(p-1)+numel(data); end
metainfo(1+(p-1)*50:endpos,2) = [data{:}];
% Nickname
expr = ['"Reputation: (\d+)">([\w\ ' reshape([repmat(92,1,137);33:59,61:64,91:97,123:126,161:255],1,[]) ']+)</a></h2>'];
data = regexp(page, expr,'tokens');
metainfo(1+(p-1)*50:endpos,[4,3]) = cat(1,data{:});
% Qcount, Ans, Acc
data = regexp(page, '<span >(\d+)</span>[A-z<>"-\s\/]+','tokens');
metainfo(1+(p-1)*50:endpos,5:7) = reshape(cat(1,data{:}),3,[]).';
else
error('Metainfo import stopped. \nCannot read ".../contributors?page=%d"',p)
end
[page, ok] = urlread([url sprintf('%d',p+1)]);
end
% Convert to doubles
metainfo(:,[2,4:7]) = cellfun(@str2double,metainfo(:,[2,4:7]),'un',false);
elapsedTime = toc;