MATLAB, how to evaluate multiple indices in one line? - matlab

I don't know how to explain this better than by giving you an example.
Suppose I have the following array:
a = magic(6)
And then I take a 'slice' of that like this:
a(:,1)
It will print:
35
3
31
8
30
4
Now I want the first number, so I want to write:
a(:,1)(1)
Instead of:
b = a(:,1)
b(1)
Also, is there a way to do something like this (assignment and comparison, i.e. set b, then evaluate against it):
(b = a(:,1))(1)
Ok, here's an update with a function where it isn't trivial to use a(1, 1)
come_on = sprintf('%i, ', magic(3));
come_on(1:end-2)
8, 3, 4, 1, 5, 9, 6, 7, 2
Also, what if I only want the first 4 numbers on magic(3)?
It would be better to write
sprintf('%i, ', magic(3)(1:4))(1:end-2)
instead of tens of lines, MHO.

You cannot concatenate indexing as foo(1)(2)(3). However, you can index multiple dimensions at once. So in this case, a(1,1) will give you what you want.

Related

Please, how to count the number of element in a fields of a structure?

I would like to count the number of element in a field of a structure in Matlab
The file name is "data.m"
I have something like this:
The file has 3 fields (Columns): x, y and z
The file has maximal 6 lines, which is the number of line of the y-column
x has 5 elements (0, 9, 5, 6, 6)
y has 6 elements (6, 1, 2, 2, 8, 2)
z has 4 elements (8, 8, 4, 9)
Using:
number_of_element = numel(data.x);
returns 1.
It only takes the first element (The first line, which is "0" here)
I would like to have the number of element of the column x, which is "5" in this case.
Then I tried this:
number_of_element = numel(data(:,x));
But it doesn't work. I though Matlab could recognise "x" as a field name.
This also did not work:
count = 0;
for i = 1:end % I get an error because of this "end". Why is it not recognised here ?
number_of_element = numel(data(i).x);
count = count+number_of_element;
end
How could I get the number of element in the x-column ?
Thank you in advance.

How can I select certain rows in a dataset? Mathematica

My question is probably really easy, but I am a mathematica beginner.
I have a dataset, lets say:
Column: Numbers from 1 to 10
Column Signs
Column Other signs.
{{1,2,3,4,5,6,7,8,9,10},{d,t,4,/,g,t,w,o,p,m},{g,h,j,k,l,s,d,e,w,q}}
Now I want to extract all rows for which column 1 provides an odd number. In other words I want to create a new dataset.
I tried to work with Select and OddQ as well as with the IF function, but I have absolutely no clue how to put this orders in the right way!
Taking a stab at what you might be asking..
(table = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} ,
Characters["abcdefghij"],
Characters["ABCDEFGHIJ"]}) // MatrixForm
table[[All, 1 ;; -1 ;; 2]] // MatrixForm
or perhaps this:
Select[table, OddQ[#[[1]]] &]
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}
The convention in Mathematica is the reverse of what you use in your description.
Rows are first level sublists.
Let's take your original data
mytable = {{1,2,3,4,5,6,7,8,9,10},{d,t,4,"/",g,t,w,o,p,m},{g,h,j,k,l,s,d,e,w,q}}
Just as you suggested, Select and OddQ can do what you want, but on your table, transposed. So we transpose first and back:
Transpose[Select[Transpose[mytable], OddQ[First[#]]& ]]
Another way:
Mathematica functional command MapThread can work on synchronous lists.
DeleteCases[MapThread[If[OddQ[#1], {##}] &, mytable], Null]
The inner function of MapThread gets all elements of what you call a 'row' as variables (#1, #2, etc.). So it test the first column and outputs all columns or a Null if the test fails. The enclosing DeleteCases suppresses the unmatching "rows".

Challenging Algorithmic Modular Multiples

While practicing coding problems, I ran into this challenging problem:
Say I have a 7-variable equation, (A+B+C+C+D+B)(E+F+B+C)(G+F+F), and a huge list with up to 3500 numbers:
A 1, 2, 3; B 1, 2; C 9, 1; D 1; E 2; F 1; G 1
This list basically gives all the possible values that each variable can have. The question is, how many ways can I choose values of variables such that the resulting number is a multiple of seven?
For example, I could choose from the above list
A = 1, B = 1, C = 1, D = 1, E = 2, F = 1, G = 1. This would make the number (1+2+1+1+1+1)(2+1+1+1)(1+1+1) = 35, which is indeed a multiple of seven.
My solution was to test every possible combination of the seven variables, and check if that sum was a multiple of seven. However, that solution is obviously very slow. Does anyone have a more efficient solution for this problem?
while if the first number is a multiple of 7 than no matter what you times it by it well remain a multiple of 7
so (E+F+B+C)(G+F+F) is completely irrelevant.
if (E+F+B+C) is a multiple of 7 then the total is also a multiple of 7 same with (G+F+F).
If none of them are multiples of 7 than I don't think the answer can be a multiple of 7. At least, I cannot think of a case where this could happen.
ex no amount of 10s will ever be devisible by 7 except say 7 or 14 10s

Select One Element in Each Row of a Numpy Array by Column Indices [duplicate]

This question already has answers here:
NumPy selecting specific column index per row by using a list of indexes
(7 answers)
Closed 2 years ago.
Is there a better way to get the "output_array" from the "input_array" and "select_id" ?
Can we get rid of range( input_array.shape[0] ) ?
>>> input_array = numpy.array( [ [3,14], [12, 5], [75, 50] ] )
>>> select_id = [0, 1, 1]
>>> print input_array
[[ 3 14]
[12 5]
[75 50]]
>>> output_array = input_array[ range( input_array.shape[0] ), select_id ]
>>> print output_array
[ 3 5 50]
You can choose from given array using numpy.choose which constructs an array from an index array (in your case select_id) and a set of arrays (in your case input_array) to choose from. However you may first need to transpose input_array to match dimensions. The following shows a small example:
In [101]: input_array
Out[101]:
array([[ 3, 14],
[12, 5],
[75, 50]])
In [102]: input_array.shape
Out[102]: (3, 2)
In [103]: select_id
Out[103]: [0, 1, 1]
In [104]: output_array = np.choose(select_id, input_array.T)
In [105]: output_array
Out[105]: array([ 3, 5, 50])
(because I can't post this as a comment on the accepted answer)
Note that numpy.choose only works if you have 32 or fewer choices (in this case, the dimension of your array along which you're indexing must be of size 32 or smaller). Additionally, the documentation for numpy.choose says
To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple.
The OP asks:
Is there a better way to get the output_array from the input_array and select_id?
I would say, the way you originally suggested seems the best out of those presented here. It is easy to understand, scales to large arrays, and is efficient.
Can we get rid of range(input_array.shape[0])?
Yes, as shown by other answers, but the accepted one doesn't work in general so well as what the OP already suggests doing.
I think enumerate is handy.
[input_array[enum, item] for enum, item in enumerate(select_id)]
How about:
[input_array[x,y] for x,y in zip(range(len(input_array[:,0])),select_id)]

Simple problems with MATLAB

I have three questions:
1)
I want to compute the following using MATLAB:
11^2 + 13^2 + 15^2 + ... + 109^2 + 111^2
I have tried using:
x = [11^2 13^2 15^2 ... 109^2 111^2]
z = cum(single(x))
but I got an error...
2)
I want to display '2 sin/pix'... I tried:
tittle('2 sin/pix')
Can I represent the display without displaying it in figure?
3)
The Fibonacci series is given as follow:
1, 2, 3, 5, 8, 13, 21, ...
How can I write a script file to calculate and print out the n-th Fibonacci term for n>2, where n is input by the user.
This is what I've tried:
input('n: ')
z = cumsum(n)
fprintf('the series=%d')
but I received an error...
1)
sum([11:2:111].^2)
2) Depending on whether you want a title or a text in a figure:
text(.5,.5,'2 sin\pix', 'interpreter','tex')
title('2 sin\pix', 'interpreter','tex')
BTW, the ASCII symbol of π is: 227 (Press and hold ALT and type 227 on Windows)
3) Take a look at this page:
http://blogs.mathworks.com/loren/2006/05/17/fibonacci-and-filter/
In the first subquestion, maybe you just mean sum instead of cum ?
I would do it like this:
x = [11:2:111]
sum(x .^ 2)
The first line is a range, giving a vector of every other number from 11 to 111, the second does a per-element squaring in that vector and sums it.
For the second question, I'm not sure what you really want to do. How about:
disp('2 sin/pix')
To compute: 11^2+13^2+...+109^2+111^2, try:
sum((11:2:111).^2)
To display '2 sin/pix'), the command is 'title' not 'tittle':
title('2 sin/pix')
Is this homework?