eqn =
主要内容
Results for
I'm beginning this MATLAB-based numerical methods class, and as I was thinking back to my previous MATLAB/Simulink classes, I definitely remember some projects more fondly than others. One of my most memorable was where I had to use MATLAB to analyze electrocardiogram (ECG) peaks. What about you guys? What are some of the best (or worst 🤭) MATLAB projects or assignments you've been given in the past?
I have a problem with the movement of a pawn by two fields in its first move does anyone have a suggestion for a solution
function chess_game()
% Funkcja główna inicjalizująca grę w szachy
% Inicjalizacja stanu gry
gameState = struct();
gameState.board = initialize_board();
gameState.currentPlayer = 'white';
gameState.selectedPiece = [];
% Utworzenie GUI
fig = figure('Name', 'Gra w Szachy', 'NumberTitle', 'off', 'MenuBar', 'none', 'UserData', gameState);
ax = axes('Parent', fig, 'Position', [0 0 1 1], 'XTick', [], 'YTick', []);
axis(ax, [0 8 0 8]);
hold on;
% Wyświetlenie planszy
draw_board(ax, gameState.board);
% Obsługa kliknięcia myszy
set(fig, 'WindowButtonDownFcn', @(src, event)on_click(ax, src));
end
function board = initialize_board()
% Inicjalizuje planszę z ustawieniem początkowym figur
board = {
'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R';
'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'', '', '', '', '', '', '', '';
'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p';
'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r';
};
end
function draw_board(~, board)
% Rysuje szachownicę i figury
colors = [1 1 1; 0.8 0.8 0.8];
for row = 1:8
for col = 1:8
% Rysowanie pól
rectColor = colors(mod(row + col, 2) + 1, :);
rectangle('Position', [col-1, 8-row, 1, 1], 'FaceColor', rectColor, 'EdgeColor', 'k');
% Rysowanie figur
piece = board{row, col};
if ~isempty(piece)
text(col-0.5, 8-row+0.5, piece, 'HorizontalAlignment', 'center', ...
'FontSize', 20, 'FontWeight', 'bold');
end
end
end
end
function on_click(ax, fig)
% Funkcja obsługująca kliknięcia myszy
pos = get(ax, 'CurrentPoint');
x = floor(pos(1,1)) + 1; % Zaokrąglij współrzędne w poziomie i dopasuj do indeksów
y = 8 - floor(pos(1,2)); % Dopasuj współrzędne w pionie (odwrócenie osi Y)
% Pobranie stanu gry z figury
gameState = get(fig, 'UserData');
if x >= 1 && x <= 8 && y >= 1 && y <= 8
disp(['Kliknięto na pole: (', num2str(x), ', ', num2str(y), ')']);
if isempty(gameState.selectedPiece)
% Wybór figury
piece = gameState.board{y, x};
if ~isempty(piece)
if (strcmp(gameState.currentPlayer, 'white') && any(ismember(piece, 'RNBQKP'))) || ...
(strcmp(gameState.currentPlayer, 'black') && any(ismember(piece, 'rnbqkp')))
gameState.selectedPiece = [y, x];
disp(['Wybrano figurę: ', piece, ' na pozycji (', num2str(x), ', ', num2str(y), ')']);
else
disp('Nie możesz wybrać tej figury.');
end
else
disp('Nie wybrano figury.');
end
else
% Sprawdzenie, czy kliknięto ponownie na wybraną figurę
if isequal(gameState.selectedPiece, [y, x])
disp('Anulowano wybór figury.');
gameState.selectedPiece = [];
else
% Ruch figury
[sy, sx] = deal(gameState.selectedPiece(1), gameState.selectedPiece(2));
piece = gameState.board{sy, sx};
if is_valid_move(gameState.board, piece, [sy, sx], [y, x], gameState.currentPlayer)
% Wykonanie ruchu
gameState.board{sy, sx} = ''; % Usuwamy figurę z poprzedniego pola
gameState.board{y, x} = piece; % Umieszczamy figurę na nowym polu
gameState.selectedPiece = [];
% Przełącz gracza
gameState.currentPlayer = switch_player(gameState.currentPlayer);
% Odśwież planszę
cla(ax);
draw_board(ax, gameState.board);
else
disp('Ruch niezgodny z zasadami.');
end
end
end
% Zaktualizowanie stanu gry w figurze
set(fig, 'UserData', gameState);
end
end
function valid = is_valid_move(board, piece, from, to, currentPlayer)
% Funkcja sprawdzająca, czy ruch jest poprawny
[sy, sx] = deal(from(1), from(2));
[dy, dx] = deal(to(1), to(2));
dy_diff = dy - sy;
dx_diff = abs(dx - sx);
targetPiece = board{dy, dx};
% Sprawdzenie, czy ruch jest w granicach planszy
if dx < 1 || dx > 8 || dy < 1 || dy > 8
valid = false;
return;
end
% Nie można zbijać swoich figur
if ~isempty(targetPiece) && ...
((strcmp(currentPlayer, 'white') && ismember(targetPiece, 'RNBQKP')) || ...
(strcmp(currentPlayer, 'black') && ismember(targetPiece, 'rnbqkp')))
valid = false;
return;
end
% Zasady ruchu dla każdej figury
switch lower(piece)
case 'p' % Pion
direction = strcmp(currentPlayer, 'white') * 2 - 1; % 1 dla białych, -1 dla czarnych
startRow = strcmp(currentPlayer, 'white') * 2 + 1; % Rząd startowy dla białych i czarnych
if isempty(targetPiece)
% Ruch o jedno pole do przodu
if dy_diff == direction && dx_diff == 0
valid = true;
% Ruch o dwa pola do przodu z pozycji startowej
elseif dy_diff == 2 * direction && dx_diff == 0 && sy == startRow
if isempty(board{sy + direction, sx}) && isempty(board{dy, dx})
valid = true;
else
valid = false;
end
else
valid = false;
end
else
% Zbijanie na ukos
valid = (dx_diff == 1) && (dy_diff == direction);
end
case 'r' % Wieża
valid = (dx_diff == 0 || dy_diff == 0) && path_is_clear(board, from, to);
case 'n' % Skoczek
valid = (dx_diff == 2 && abs(dy_diff) == 1) || (dx_diff == 1 && abs(dy_diff) == 2);
case 'b' % Goniec
valid = (dx_diff == abs(dy_diff)) && path_is_clear(board, from, to);
case 'q' % Hetman
valid = ((dx_diff == 0 || dy_diff == 0) || (dx_diff == abs(dy_diff))) && path_is_clear(board, from, to);
case 'k' % Król
valid = max(abs(dx_diff), abs(dy_diff)) == 1;
otherwise
valid = false;
end
end
function clear = path_is_clear(board, from, to)
% Sprawdza, czy ścieżka między polami jest wolna od innych figur
[sy, sx] = deal(from(1), from(2));
[dy, dx] = deal(to(1), to(2));
stepY = sign(dy - sy);
stepX = sign(dx - sx);
y = sy + stepY;
x = sx + stepX;
while y ~= dy || x ~= dx
if ~isempty(board{y, x})
clear = false;
return;
end
y = y + stepY;
x = x + stepX;
end
clear = true;
end
function nextPlayer = switch_player(currentPlayer)
% Przełącza aktywnego gracza
if strcmp(currentPlayer, 'white')
nextPlayer = 'black';
else
nextPlayer = 'white';
end
end
Speaking as someone with 31+ years of experience developing and using imshow, I want to advocate for retiring and replacing it.
The function imshow has behaviors and defaults that were appropriate for the MATLAB and computer monitors of the 1990s, but which are not the best choice for most image display situations in today's MATLAB. Also, the 31 years have not been kind to the imshow code base. It is a glitchy, hard-to-maintain monster.
My new File Exchange function, imview, illustrates the kind of changes that I think should be made. The function imview is a much better MATLAB graphics citizen and produces higher quality image display by default, and it dispenses with the whole fraught business of trying to resize the containing figure. Although this is an initial release that does not yet support all the useful options that imshow does, it does enough that I am prepared to stop using imshow in my own work.
The Image Processing Toolbox team has just introduced in R2024b a new image viewer called imageshow, but that image viewer is created in a special-purpose window. It does not satisfy the need for an image display function that works well with the axes and figure objects of the traditional MATLAB graphics system.
I have published a blog post today that describes all this in more detail. I'd be interested to hear what other people think.
Note: Yes, I know there is an Image Processing Toolbox function called imview. That one is a stub for an old toolbox capability that was removed something like 15+ years ago. The only thing the toolbox imview function does now is call error. I have just submitted a support request to MathWorks to remove this old stub.
The int function in the Symbolic Toolbox has a hold/release functionality wherein the expression can be held to delay evaluation
syms x I
eqn = I == int(x,x,'Hold',true)
which allows one to show the integral, and then use release to show the result
release(eqn)
Maybe it would be nice to be able to hold/release any symbolic expression to delay the engine from doing evaluations/simplifications that it typically does. For example:
x*(x+1)/x, sin(sym(pi)/3)
If I'm trying to show a sequence of steps to develop a result, maybe I want to explicitly keep the x/x in the first case and then say "now the x in the numerator and denominator cancel and the result is ..." followed by the release command to get the final result.
Perhaps held expressions could even be nested to show a sequence of results upon subsequent releases.
Held expressions might be subject to other limitations, like maybe they can't be fplotted.
Seems like such a capability might not be useful for problem solving, but might be useful for exposition, instruction, etc.
Watt's Up with Electric Vehicles?EV modeling Ecosystem (Eco-friendly Vehicles), V2V Communication and V2I communications thereby emitting zero Emissions to considerably reduce NOx ,Particulates matters,CO2 given that Combustion is always incomplete and will always be.
Reduction of gas emissions outside to the environment will improve human life span ,few epidemic diseases and will result in long life standard
I want to build a neural network that takes a matrix A as input and outputs a matrix B such that a constant C=f(A,B)is maximized as much as possible.(The function f()is a custom complex computation function involving random values,probability density,matrix norms,and a series of other calculations).
I tried to directly use 1/f(A,B)or-f(A,B)as the loss function,but I encountered an error stating:"The value to be differentiated is not tracked.It must be a tracked real number dlarray scalar.Use dlgradient to track variables in the function called by dlfeval."I suspect this is likely because f(A,B)is not differentiable.
However,I've also seen people say that no matter what function it is,the dlgradient function can differentiate it.
So,I'm not sure whether it's because the function f()is too complex to be used as a loss function to calculate gradients,or if there's an issue with my code.
If I can't directly use its reciprocal or negative as the loss function,how should I go about training this neural network?Currently,I only know how to implement:providing target values and using functions like mse or huber as loss functions.
Objectif : Etude d'une chaine de transmission numérique avec des turbo-codes combiné avec la technique HARQ (Hybrid Automatic Repeat reQuest):
* Mettre en place une chaîne de transmission numérique avec des turbo codes intégrant la technique HARQ.
* Évaluer les performances de cette chaîne, en termes de taux d'erreur et de débit sous diverses conditions de canal.
En structurant ainsi votre étude, vous pourrez mener une analyse approfondie des turbo codes et de la technique HARQ.
Outils : Utilisez des outils comme MATLAB, Simulink ou Python (avec des bibliothèques comme Scipy pour la modélisation des canaux et NumPy pour la gestion des calculs).
Simulations : Créez une série de simulations en variant les paramètres comme le SNR, le type de HARQ utilisé, etc.
Compétences développées : Maîtrise des techniques de détection et de correction d’erreurs pour améliorer la fiabilité des transmissions
Hello,
Anyone has basic MATLAB code upon RSMA i.e. to understand basic implementation of RSMA, how to generate common and private messages in MATLAB, etc...?
Always and almost immediately!
25%
Never
30%
After validating existing code
16%
Y'all get the new releases?
29%
1291 个投票
Many of my best friends at MathWorks speak Spanish as their first language and we have a large community of Spanish-speaking users. You can see good evidence of this by checking out our relatively new Spanish YouTube channel which recently crossed the 10,000 subscriber mark
For a project that i am working on, I have to deal with a set of 36 superheated steam tables in one of 3 sheets in an excel file. Since the tables are organized as a set of 5 columns (T,V,U,H,S) with a Pressure "title", but Pressure is a variable I need to be able to read, I want to go about converting the pressure into the first column (unless there is an easier way) of each table where for the length of that table (27 rows) the pressure is the same even as the other variables change (like a matrix). However when I did that I faced a number of issues:
1. the tables didn't separate properly so it combined into 3 tables which is incorrect
2. The pressure column was created but didn't fill with numbers so all showed NaN
3. The column names for the variables are different than my inputs (The columns are listed with units like T_C_ or U_kJ_kg_ and so on, but I need to be able to input any 2 properties and get the rest and I need to be able to input them in the form of T and U and have it understand what columns I am looking for.
3a. When I tried to replace the variable names in the code, Since there are 3 tables it started giving me an error message that there are duplicates of properties when there shouldn't be because they should all be different tables and I want it to recognize that.
Here is a bit of what my table looks like: Please help
Apart optimize angle by Lagrange equation, how many methodes have we about anti-swing for the stabilisation of gantry crane while loading and unloading contenainers? thank you a lot.
hello !! Can we design a control method in backstepping for second order? and how to design it? thank you for all.
I've always used MATLAB with other languages. In the early days, C and C++ via mex files were the most common ways I spliced two languages together. Other than that I've also used MATLAB with Java, Excel and even Fortran.
In more recent years, Python is the language I tend to use most alongside MATLAB and support for this combination is steadily improving. In my latest blog post, I show how easy it has become to use Python's Numpy with MATLAB.
Have you used this functionality much? If so, what for? How well did it work for you?
I am inspired by the latest video from YouTube science content creator Veritasium on his distinct yet thorough explanation on how rainbows work. In his video, he set up a glass sphere experiment representing how light rays would travel inside a raindrop that ultimately forms the rainbow. I highly recommend checking it out.
In the meantime, I created an interactive MATLAB App in MATLAB Online using App Designer to visualize the light paths going through a spherical raindrop with numerical calculations along the way. While I've seen many diagrams out there showing the light paths, I haven't found any doing calculations in each step. Hence I created an app in MATLAB to show the calculations along with the visualizations as one varies the position of the incoming light ray.
Demo video:
For more information about the app and how to open it and play around with it in MATLAB Online, please check out my blog article:
Our MathWorks Usability Team is working on an accessibility project and they want to interview people who use MATLAB and also have experience with screen readers.
If you fit the criteria and are interested, sign up here https://www.mathworks.com/products/usability.html?tfa_30=A11Y
I wish I knew more about the intended evolution of the capabilities of the function arguments block. I love implementing function syntaxes using this relatively new form, but it doesn't yet handle some function syntax design patterns that I think are valuable and worth keeping.
For example, some functions take an input quantity that can something numeric, or it can be an option string that descriptively names a particular value of that quantity. One example is dateshift(t,"dayofweek",dow), where dow can be an integer from 1 to 7, or it can be one of the option strings "weekday" or "weekend".
Another example is Image Processing Toolbox that take a connectivity specifier as input. The function bwconncomp is one particular case. Connectivity can be specified using certain scalars, certain arrays, or the option string "maximal".
I think this is a worthwhile function design pattern, but I don't think the arguments block validation functionality supports it well (unless you use a lot of extra code that duplicates standard MATLAB behavior, which undermines the value of the arguments block).
MathWorkers - believe me, I know that it is not in your DNA to discuss future features. But would anyone care to offer a hint about directions for the arguments block functionality?
I am very excited to share my new book "Data-driven method for dynamic systems" available through SIAM publishing: https://epubs.siam.org/doi/10.1137/1.9781611978162
This book brings together modern computational tools to provide an accurate understanding of dynamic data. The techniques build on pencil-and-paper mathematical techniques that go back decades and sometimes even centuries. The result is an introduction to state-of-the-art methods that complement, rather than replace, traditional analysis of time-dependent systems. One can find methods in this book that are not found in other books, as well as methods developed exclusively for the book itself. I also provide an example-driven exploration that is (hopefully) appealing to graduate students and researchers who are new to the subject.
Each and every example for the book can be reproduced using the code at this repo: https://github.com/jbramburger/DataDrivenDynSyst
Hope you like it!