. . . . . . "I originally made it because I wanted to take the derivative of Ix as a function of time using the `diff()` function. This particular example is simple because each coefficient is a constant, So I can do it manually, but there will be change in the future that I'm not aware of at the moment where these coefficients will become a function of time and there will be many more equations to include."^^ . . . . . "1"^^ . . . . . "1"^^ . "@PeterCordes You're right, you can interpret the question in that way too. It seems that R2024a and onwards can figure out how many P cores there are. But it still doesn't need to know which cores those are."^^ . . . . . . "1"^^ . . "0"^^ . "0"^^ . "0"^^ . . . "0"^^ . "<p>I've created an example using the top-left corner of your provided map</p>\n<p>Click the image to see the full resolution version...</p>\n<p><a href="https://i.sstatic.net/YFCZ0mkx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YFCZ0mkx.png" alt="Simulink model" /></a></p>\n<ol>\n<li><p>I've added displays in yellow so you can see the input map, as well as various values through the model. The input map values I've used are a subset of your example data.</p>\n</li>\n<li><p>You can use a &quot;Prelookup&quot; block for your given RPM (e.g. 1000RPM) to determine the index (zero-based) and fraction (towards the following index) along the RPM axis.</p>\n</li>\n<li><p>You can spoof the pre-lookup for the 2nd axis because we want all values across the gears. To get all indicies we can use <code>0:(N-1)</code> for <code>N</code> gears, with a fraction <code>[0,0,...,0,1]</code> of the same length (note the final value only is a 1).</p>\n</li>\n<li><p>Feeding this and the table data for torque into an &quot;Interpolation Using Prelookup&quot; block, we can get the entire torque map (interpolated) at the current RPM vs gear.</p>\n</li>\n<li><p>We can now do a 1D lookup of gear number vs torque, which can be done using a &quot;1-D Lookup Table&quot; block. Note that the axis for this block must be monotonically increasing. Your torque map is monotonically <em>decreasing</em> as the gears increase, so we can flip both inputs using a &quot;Selector&quot; block set to indicies <code>N:-1:1</code> for <code>N</code> gears. You're fortunate here, if your map wasn't monotonically decreasing then this step would be more complicated, because there would be multiple possible gears for your desired torque.</p>\n<p>I've set the 1-D interp block to &quot;nearest&quot; so you get the closest integer gear choice for your target torque. You could use linear interpolation here if you actually need to know how close to the next gear you are for anything downstream.</p>\n</li>\n</ol>\n<p>The main setting I had to change internally for any of the blocks was to set all &quot;source&quot; options for the interpolation blocks to &quot;Input Port&quot; so the data could be specified by the inputs on the left, rather than internal to the block dialog.</p>\n"^^ . . . "<p>You can add a row to your table which is <code>num1</code> repeated to the same size as <code>num2</code>, then just print the whole table in your format:</p>\n<pre><code>tbl = [num1*ones(size(num2)); num2; product];\nfprintf('%d x %d = %d \\n', tbl);\n</code></pre>\n<p>Output:</p>\n<pre><code>3 x 1 = 3 \n3 x 2 = 6 \n3 x 3 = 9 \n3 x 4 = 12 \n3 x 5 = 15 \n3 x 6 = 18 \n3 x 7 = 21 \n3 x 8 = 24 \n3 x 9 = 27 \n3 x 10 = 30 \n3 x 11 = 33 \n3 x 12 = 36 \n</code></pre>\n<p>Note that the orientation of <code>tbl</code> matters here, the way you had it already works because the placeholders will populate the output string columns-first, since <a href="https://stackoverflow.com/questions/21413164/is-matlab-row-specific-or-column-major">MATLAB is column-major</a>, i.e. the first column is <code>[3; 1; 3]</code> so they are the first three digits used in the printed output <code>3 x 1 = 3</code>.</p>\n"^^ . "0"^^ . . "compression"^^ . "1"^^ . . . . "0"^^ . "unit-testing"^^ . "1"^^ . . "0"^^ . "If you multiply your matrix through by 3*5/0.005008047876602563 and divide by 256 or 512 then numerical QR codes might at least stand a chance. The matrix values appear to be integers divided by some random number or other (8386501?). ISTR Julia hands numerical matrix work over to LApack so you should get the same answer from that. My instinct is that Matlab is probably getting it wrong but whether or not LAPack/Julia is getting it right I wouldn't like to speculate. Rescaling and round so that the values are all exactly represented ought to help (and also keeping their magnitudes near 1)."^^ . . "Running timed process in background (MATLAB)"^^ . "@jarhead I've updated my answer with respect to your latest edit"^^ . "0"^^ . . "<p>I have been trying to generate the positive ,negative and zero sequence components of the input sinusoid .I have three sinusoidal phases 120 degree separated (Balanced) . The formula to calculate Positive , Negative and zero sequence is given below.\n<a href="https://i.sstatic.net/5YmJMCHO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5YmJMCHO.png" alt="Formula to calculate the positive , negative and zero sequency components of three phase supply " /></a></p>\n<p>where a = 0.5 + i0.866 or 1&lt;120* (complex number).\nNow if i generate Va , Vb , Vc inside of a matlab itself and use the formulae I get the correct result. Code below and correct result too .</p>\n<pre><code>% Define Parameters\nt = 0:0.001:1; % Time vector\nA = 1; % Amplitude\nf = 50; % Frequency in Hz\n\n% Generate Sinusoidal signals with 120 degrees phase shift\nv_a = A * exp(1i * (2 * pi * f * t)); % V_a = A * e^(j * 0)\nv_b = A * exp(1i * (2 * pi * f * t - 2 * pi / 3)); % V_b = A * e^(j * 120°)\nv_c = A * exp(1i * (2 * pi * f * t + 2 * pi / 3)); % V_c = A * e^(j * -120°)\n\n% Call the function to calculate sequence components\n[va_pos, va_neg, va_zero] = fcn(v_a, v_b, v_c);\n\n\n% Plotting the sequence components\nfigure;\n\n% Plot for Positive Sequence Component\nsubplot(3,1,1);\nplot(t, real(va_pos), 'r', 'DisplayName', 'Real Part'); \nhold on;\n\ntitle('Positive Sequence Component');\nxlim([0 0.3]);\nylim([-1 1]);\nxlabel('Time (s)');\nylabel('Amplitude');\nlegend show;\ngrid on;\n\n% Plot for Negative Sequence Component\nsubplot(3,1,2);\nplot(t, real(va_neg), 'r', 'DisplayName', 'Real Part');\n\nhold on;\n%plot(t, imag(va_neg), 'b', 'DisplayName', 'Imaginary Part');\ntitle('Negative Sequence Component');\nxlabel('Time (s)');\nylim([-1 1]);\nylabel('Amplitude');\nlegend show;\ngrid on;\n\n% Plot for Zero Sequence Component\nsubplot(3,1,3);\nplot(t, real(va_zero), 'r', 'DisplayName', 'Real Part');\nhold on;\n%plot(t, imag(va_zero), 'b', 'DisplayName', 'Imaginary Part');\ntitle('Zero Sequence Component');\nxlabel('Time (s)');\nylim([-1 1]);\nylabel('Amplitude');\nlegend show;\ngrid on;\n\n% Function to calculate sequence components\nfunction [va_pos, va_neg, va_zero] = fcn(v_a, v_b, v_c)\n% Define complex exponential for 120 degrees and 240 degrees\nalpha = complex(-0.5, 0.866); % e^(j*120 degrees)\nalpha_square = complex(-0.5, -0.866); % e^(j*240 degrees)\n\n% Calculate positive sequence component\nva_pos = (1/3) * (v_a + alpha * v_b + alpha_square * v_c);\n\n% Calculate negative sequence component\nva_neg = (1/3) * (v_a + alpha_square * v_b + alpha * v_c);\n\n% Calculate zero sequence component\nva_zero = (1/3) * (v_a + v_b + v_c);\nend\n</code></pre>\n<p><a href="https://i.sstatic.net/6HtNtLUB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6HtNtLUB.png" alt="Correct result" /></a></p>\n<p>Now I have Va , Vb , Vc (I generate them now in simulink using sine wave block)and use them as inputs to the simulink function written below (same as one written above).</p>\n<pre><code>function [va_pos, va_neg, va_zero] = fcn(v_a, v_b, v_c)\n\n% Define complex exponential for 120 degrees and 240 degrees\nalpha = complex(-0.5,0.866); % e^(j*120 degrees)\nalpha_square = complex(-0.5,-0.866); % e^(j*240 degrees)\n\n% Calculate positive sequence component\nva_pos = (1/3) * (v_a + alpha * v_b + alpha_square * v_c);\n\n% Calculate negative sequence component\nva_neg = (1/3) * (v_a + alpha_square * v_b + alpha * v_c);\n\n% Calculate zero sequence component\nva_zero = (1/3) * (v_a + v_b + v_c);\n</code></pre>\n<p>end</p>\n<p>It gives wrong result as show below .(First plot is Positive sequence , second is negative seq. and third is zero sequence . same as the above mentioned plot).\n<a href="https://i.sstatic.net/MBOZH0Cp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MBOZH0Cp.png" alt="enter image description here" /></a></p>\n<p>and i suspect it is because it is taking the Va , Vb and Vc in real time (in simulink model).</p>\n<p>I tried abs() and phase() to extract the phase and magnitude of the sinusoidal wave separately(in real time function in simulink) but to no avail . I would like to know if there is a way of doing extracting a phase and magnitude of a sinosoidal wave in real like in simulink using MATLAB scripting ?</p>\n"^^ . . "0"^^ . . "1"^^ . "3"^^ . . "<p>I'm attempting to call a database function that takes a single <code>UUID</code> as a parameter. When I do this:</p>\n<pre class="lang-matlab prettyprint-override"><code>report_id = &quot;5ed30f08-0de0-47f4-99e8-9aeeb8eb2dfe&quot;;\n\nquery = &quot;select * from public.fn_func($1)&quot;;\nreport_nav = pq_exec_params (conn, query, {report_id});\n</code></pre>\n<p>I get this:</p>\n<pre class="lang-bash prettyprint-override"><code>__pq_exec_params__: fatal error: ERROR: function public.fn_func(text) does not exist\n</code></pre>\n<p>So clearly, something is converting <code>report_id</code> to the PostgreSQL <code>text</code> data type. So I tried to cast to a <code>UUID</code> by changing the query to this:</p>\n<pre class="lang-matlab prettyprint-override"><code>query = &quot;select * public.fn_func($1::uuid)&quot;;\n</code></pre>\n<p>But then I get this message:</p>\n<pre class="lang-bash prettyprint-override"><code>no converter found for element oid 1700\n</code></pre>\n<p>I've definitely added the <code>uuid-ossp</code> module to my database, so I can run this directly against the database:</p>\n<pre class="lang-sql prettyprint-override"><code>select '5ed30f08-0de0-47f4-99e8-9aeeb8eb2dfe'::uuid;\n</code></pre>\n<p>I'm using <code>octave</code> v6.4 to execute the script, running on Ubuntu 22.04 with PostreSQL v14.13.</p>\n"^^ . . . "@jarhead if we take `n` at face value then the peak is at the 2nd index, which according to your `theta` array is approx 0.196rad or 11deg, which does not look like it aligns with the quiver you've drawn. If you let me know how you arrived at that direction maybe I can fill in the gaps..."^^ . . "1"^^ . . . "In MATLAB operators < and > CAN and DO indeed operate matrixes . Try : [1 2 3] > [4 5 6]\n Result : \n 1×3 logical array\n 0 0 0"^^ . . "0"^^ . . . . . . . "Nice, we do something similar. Did not realize you need to warnings also after code generation."^^ . . "0"^^ . "<p>There is a task: to simulate waves on the ocean surface 3D case. I faced the problem that when simulating waves in a large area of the ocean (1 km x 1 km), the program takes a very long time to execute. And in fact it is not executed at all. Because during those half an hour of waiting for the result, it was never calculated.</p>\n<p>Example of my code:</p>\n<pre><code>clear,clc\n%% Data \nx = 0:1:100; % coordinates х [m]\ny = 0:1:100; % coordinates y [m]\ng = 9.81; % gravitational constant [m/s^2]\nspeed = 5; % wind velocity [m/s]\nw0 = (g / speed); % norm.frequency [Hz]\ndw = 0.1; % frequency step [rad/s]\nw = 0.8:dw:11.1; % frequency [rad/s] \ndtt = pi / 18; % angular step [rad]\ntheta = 0:dtt:pi; % direction angles, angles between the wavevector &amp; coordintae axis [rad]\n\n%% P-M spectrum, Frequency-Angular spectrum &amp; Amplitude\nPsi = 8.1e-3 .* ((w/w0).^(-5)) .* exp((-0.74) ./ ((w/w0).^(4))); % P-M spectrum [none]\nPhi = ((speed)^(5)/g^(3)) * Psi; % self-similar spectrum [s*m^2]\nSw = Phi / 2; % frequency spectrum [s*m^2]\n\nSt = cos(theta).^(4); % angular spectrum [none]\nNorm = trapz(dtt, St); % norm.coefficient [none]\nSwt = Sw .* St'; % frequency-angular spectrum [s*m^2]\n\neta0 = sqrt((Swt * dw * dtt) ./ Norm); % amplitude [m]\n\nfigure(1);\nsubplot(2,1,1)\nplot(w, Psi);\ntitle('$$\\Psi$$($$\\omega$$) - P-M spectrum', 'Interpreter', 'LaTex');\nxlabel('\\omega [rad/s]');\nylabel('\\Psi [none]');\ngrid on;\nsubplot(2,1,2)\nplot(w, Swt); \ntitle('$$S(\\omega , \\theta)$$($$\\omega$$) - frequency-angular spectrum', 'Interpreter', 'LaTex');\nxlabel('\\omega [rad/s]');\nylabel('S(\\omega,\\theta) [s*m^2]');\ngrid on;\n\n%% Setting the initial phase parameter\nphase = 2*pi*rand(length(theta),length(w)); %% random initial phase ranging from 0 to 2pi [rad]\n\n%% Surface Waving [Linear, 3D (eta &amp; x,y)] at different harmonics &amp; random phase (at one moment in time), different directions of the wavevector (multiple angles)\nt = 0; % time moment [s]\nKabs = (w.^2) / g; % wavevector module [rad/m]\nKx = Kabs .* cos(theta)'; % projection of the wavevector onto the x-axis [rad/m]\nKy = Kabs .* sin(theta)'; % projection of the wavevector onto the y-axis [rad/m]\n\neta = zeros(length(x),length(y),length(theta),length(w)); % reserving space for calculation results\ntic\nfor i = 1:length(x)\n for j = 1:length(y)\n eta(i,j,:,:) = eta0 .* cos(w * t - Kx .* i - Ky .* j + phase);\n end\nend\ntoc\n% sum(sum(eta,4),3) - double sum of eta over all harmonics (frequencies) and wavevector directions (angles theta),\n% where '4' и '3' summation indicator for variable frequency and angle\netaW = sum(eta,4);\netaWA = sum(etaW,3);\n\nfigure(2)\nsurf(x,y,etaWA);\ntitle('\\eta(x,y) - surface waving');\nxlabel('x [m]');\nylabel('y [m]');\nzlabel('\\eta [m]');\ncbar = colorbar;\ncbar.Label.String = '\\eta [m]';\ngrid on\nshading flat\n</code></pre>\n<p>One of the code optimization methods that I was able to use is to create an &quot;empty&quot; 4D array (4D array of zeros) <code>eta = zeros(length(x),length(y),length(theta),length(w));</code> into which, after executing the loop, the calculation results will be filled:</p>\n<pre><code>eta = zeros(length(x),length(y),length(theta),length(w)); % reserving space for calculation results\ntic\nfor i = 1:length(x)\n for j = 1:length(y)\n eta(i,j,:,:) = eta0 .* cos(w * t - Kx .* i - Ky .* j + phase);\n end\nend\ntoc\n</code></pre>\n<p>Then I summarize the results by frequency and angle variables:</p>\n<pre><code>etaW = sum(eta,4);\netaWA = sum(etaW,3);\n</code></pre>\n<p>Thereby preparing the place for the results in advance. It kind of helped. For example, the code execution time for an area <code>x = 0:1:100; y = 0:1:100;</code> (100 m x 100 m) using this method was 0.7 s (without it, 3.9 s). In the case of an area <code>x = 0:1:500; y = 0:1:500;</code> (500 m x 500 m), the execution time was about 19 seconds (without it...I have no idea, I didn't wait for the code to be executed, but it turns out it was very long). However, with an area <code>x = 0:1:1000; y = 0:1:1000;</code> (1000 m x 1000 m), I have not been getting the desired result for a long time (and it feels like I won't get it at all).</p>\n<p>Is there any more ways in my case to achieve the desired result and optimize my code so that it can cope with such a scale of data (at the same time, without changing the step in the array)?</p>\n<p>Note: I have 16 GB of RAM on my computer. My second computer, where I initially performed calculations, hung up completely during the execution of the program, so I had to restart it &quot;manually&quot;. So I suppose there is even less RAM in it.</p>\n"^^ . . . "frequency-analysis"^^ . . . "0"^^ . . . "0"^^ . "1"^^ . "0"^^ . . "Before trying to solve the issue I'd recommend that you fix the indentation and the variable naming of your code. Looking at the code I have no idea what `a`, `b` and `z` variables are supposed to do. Use descriptive names for your variables. It would also be a good idea that for a smaller range (eg: `for i=1:5`) you provide what is the result you expect, so we can better understand what are you trying to do."^^ . . . . . . "<p>I try to build a restful service using matlab's restFunctionService api, but I get an error when I run it.</p>\n<p>mySqrt.m:</p>\n<pre><code>function result = mySqrt(x)\n result = sqrt(x);\nend\n\n</code></pre>\n<p>mySqrtService.m</p>\n<pre><code>serviceL = restFunctionService(&quot;EL&quot;,[&quot;mySqrt&quot;],ClientAccessMode=&quot;remote&quot;);\n</code></pre>\n<p>matlab version is 2024a.</p>\n<p>result image\n<img src="https://i.sstatic.net/fAWkB86t.png" alt="result image"></p>\n<p>Can someone tell me what is going on?</p>\n<p>I tried reinstalling Matlab, but it didn't solve the problem.</p>\n"^^ . . . . . . . . "numerical-methods"^^ . "0"^^ . . . . "1"^^ . "0"^^ . . . . "0"^^ . "0"^^ . "0"^^ . . "0"^^ . "0"^^ . . . . "<p>I have the following color scale in an image and I would like to create something similar in a clut file.</p>\n<p>Here is the scale <a href="https://i.sstatic.net/wjEILcpY.png" rel="nofollow noreferrer">BlueGreenRedYellow color scale</a></p>\n<p>And here is an example of a clut file</p>\n<pre><code>[FLT]\nmin=0\nmax=0\n[INT]\nnumnodes=5\n[BYT]\nnodeintensity0=1\nnodeintensity1=64\nnodeintensity2=128\nnodeintensity3=191\nnodeintensity4=255\n[RGBA255]\nnodergba0=0|0|0|0\nnodergba1=0|96|100|64\nnodergba2=112|102|0|128\nnodergba3=223|106|0|191\nnodergba4=255|253|0|255\n</code></pre>\n<p>Do you know how I could do that?</p>\n<p>It would be great if you have any ideas on how to try to replicate this. I do not know how to approach this issue.</p>\n"^^ . . "0"^^ . "I don't have any code to show, because I do not know what the operation is that I need to perform this task. What operation do I need to use is what I am trying to ask."^^ . . "0"^^ . "user-interface"^^ . "0"^^ . . . . . . . "0"^^ . "0"^^ . . . . . "0"^^ . . "0"^^ . "Well the problem is I don't know which one will take a short time vs. a long time. But I think what you both said is the way to go. Unless...I can use multiprocessing to both at once and stop both after 2ms."^^ . "matpower"^^ . . "2"^^ . . . . . . . . . . . "mri"^^ . . . "0"^^ . . . . . . . . "0"^^ . . . . "2"^^ . . . . "<p>Using the debugger is a logical approach. But note using <code>coder.extrinsic</code> you can use unsupported MATLAB functions during simulation as well.</p>\n"^^ . "0"^^ . . "Is there an aggregate array function in Matlab? And is it possible to reference different index in such array function?"^^ . . "<p>I'm trying to demodulate a given AM signal in MATLAB, but the results are not satisfactory as you can see:</p>\n<p><a href="https://i.sstatic.net/nSnmJu3P.png" rel="nofollow noreferrer">result</a></p>\n<p>How can I obtain the demodulated signal (red) correctly?</p>\n<p>The signal that is modulated and demodulated is</p>\n<pre><code>xc = Ac * (1 + m * exp(-(t/T0).^2)) .* cos(2 * pi * fc * t);\n</code></pre>\n<p>Thanks in advance.</p>\n<p>Code implemented:</p>\n<p>Base code:</p>\n<pre><code>% Parámetros de la señal\nAc = 5; % Amplitud de la portadora\nm = 0.2; % Índice de modulación\nT0 = 2e-6; % Tiempo constante (2 microsegundos)\nfc = 30e6; % Frecuencia de la portadora (30 MHz)\nbw = 15e6; % Ancho de banda del demodulador (15 MHz)\nfs= 100e6;\n\n% Tiempo\nt = linspace(-5e-6, 5e-6, 1e6); % 1 millón de muestras entre -5 y 5 microsegundos\n\n% Señal modulada en AM\nxc = Ac * (1 + m * exp(-(t/T0).^2)) .* cos(2 * pi * fc * t);\n\n%Señal demodulada\nxd= demod_AM(xc,fc,fs,bw,t);\n\n%teórica\nenv_teorica = Ac * (1 + m * exp(-(t/T).^2));\n\nplot(t,xd,t,env_teorica)\n</code></pre>\n<p>Function implemented for demodulating the AM signal:</p>\n<pre><code>function xd=demod_AM(xc,fc,fs,bw,t)\n % xd = señal demodulada: x_d(t)\n % xc = señal modulada: x_c(t)\n % fc = frecuencia de la portadora\n % fs = frecuencia de muestreo\n % bw = ancho de banda del filtro\n % t = vector de tiempos\n\n% Mezclar la señal modulada con la portadora (detección coherente)\nmixed_signal = xc .* cos(2 * pi * fc * t);\n\nxd= lowpass(mixed_signal,fs,bw,5);\n\nend\n</code></pre>\n<p>Lowpass band filter:</p>\n<pre><code>function newdata = lowpass(data,samprate,cutoff,order)\n\n% newdata = lowpass(data,samprate,cutoff,order)\n%\n% performs a lowpass filtering of the input data\n% using an nth order zero phase lag butterworth filter\n%\n% given -&gt; data (data)\n% -&gt; samprate (Hz)\n% -&gt; cutoff freq (Hz)\n% -&gt; order of filter (optional: default 2nd order)\n%\n% returns -&gt; filtered data\n\nif nargin==3 order=2; end; % default to 2nd order\n\n% get filter paramters A and B\n[B,A] = butter(order,cutoff/(samprate/2));\n% perform filtering\nnewdata = filtfilt(B,A,data);\n</code></pre>\n"^^ . "0"^^ . "1"^^ . "<p>You can also set the <code>dbstop</code> options (and see their current state) from the EDITOR tab of the ribbon bar</p>\n<p><a href="https://i.sstatic.net/2fTBbfmM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2fTBbfmM.png" alt="Options for &quot;Run &gt; Stop on ...&quot;" /></a></p>\n<p>In older versions of MATLAB I believe this was in the dropdown menu under &quot;Breakpoints&quot; instead of &quot;Run&quot;</p>\n"^^ . . "I still don’t understand what the advantage of 4 separate tests would be if you can’t run them separately."^^ . . . . "<p>Is it possible in <code>matlab.unittest.TestCase</code> TestClass to declare property for test methods in such a way, so if it got changed in one test method, following methods use this updated value?</p>\n<p>In example, if there is such example class:</p>\n<pre><code>classdef MyTestCase &lt; matlab.unittest.TestCase\n properties\n id\n end\n</code></pre>\n<p>Then, i need to set this <code>id</code> property in such a way for all test methods, so i can retain it state across all the test methods, to make every next methods depending on the previous, e.g.</p>\n<pre><code>% set id = 10 before\nmethods(Test)\n function testMultiplicationByTwo(testCase)\n testCase.id = testCase.id * 2;\n testCase.verifyEqual(testCase.id, 20);\n end\n \n function testIdRemainsUnchanged(testCase)\n testCase.id = testCase.id + 10; % this testCase.id value should remain 20 after previous case\n testCase.verifyEqual(testCase.id, 30);\n end\nend\n</code></pre>\n<p>Tried to do this in <code>methods(TestClasSetup)</code>, but looks like it allows only <code>testCase</code> function parameter, so if i set <code>id</code> equals 10 there, it will resets for every new <code>testCase</code>. Any ways to share this updated value across all the test methods?</p>\n<p>EDIT_1: other possible workaround may be to somehow store the ID after any actions done with it to some external/class-scope variable or parameter and then use it in following tests, e.g.</p>\n<pre><code>% set id = 10 before\nmethods(Test)\n function testMultiplicationByTwo(testCase)\n testCase.id = testCase.id * 2;\n updated_id = testCase.id\n % store updated_id somehow for its future use in following tests\n testCase.verifyEqual(testCase.id, 20);\n end\n \n function testIdRemainsUnchanged(testCase) % provide it here as param (testCase, updated_id)\n % or load somewhere from external source before test actions, then\n testCase.id = updated_id + 10; % should be 20 after previous case\n testCase.verifyEqual(testCase.id, 30);\n end\nend\n</code></pre>\n<p>Regards,\nN.</p>\n"^^ . . . "0"^^ . "0"^^ . "2"^^ . . "your question appears to be authored with AI assistance. I would not recommend using AI to "shape up" any prose."^^ . "<p>I found the answer. this code worked for me</p>\n<pre><code>clc\nclear\nclose all\n\nf1 = @(t) 3*sin(t);\nf2 = @(t) 1 + sin(t);\n\nsyms t\nT = solve(f2(t) - f1(t));\n\ntheta = linspace(T(1), T(2), 300);\n\nr1 = f1(theta);\nr2 = f2(theta);\n\nx1 = r1 .* cos(theta);\ny1 = r1 .* sin(theta);\n\nx2 = r2 .* cos(theta);\ny2 = r2 .* sin(theta);\n\nfill([x1, fliplr(x2)], [y1, fliplr(y2)], 'g', 'FaceAlpha', 0.7);\n\nhold on\n\nt = linspace(0,2*pi, 300);\nplot(f1(t).*cos(t),f1(t).*sin(t))\nplot(f2(t).*cos(t),f2(t).*sin(t))\n\naxis equal\n</code></pre>\n"^^ . "@robert oh, yeah, I didn’t think of the need to restart after setting the Java environment."^^ . . "1"^^ . "compiler-errors"^^ . . . . "postgresql"^^ . "<p>It looks like during the fitting process Matlab is trying <em>negative values</em> for <code>b</code>, and that gives a complex result for the logarithm. The error is quite explicit:</p>\n<blockquote>\n<p>Complex value computed by model function, fitting cannot continue.\nTry using or tightening upper and lower bounds on coefficients.</p>\n</blockquote>\n<p>To avoid that, as the error suggests, specify a lower value <code>0</code> for <code>b</code>. You do that with the <a href="https://www.mathworks.com/help/curvefit/fit.html#bto2vuv-1-Lower" rel="nofollow noreferrer"><code>'lower'</code> optional input</a> of the <a href="https://www.mathworks.com/help/curvefit/fit.html" rel="nofollow noreferrer"><code>fit</code> function</a>. This forces you to specify lower values for <em>all</em> coefficients, so for ther others use <code>-inf</code>.</p>\n<p>Added or modified lines are marked with <code>%%</code>:</p>\n<pre><code>% input\nx = [4 9 15 25 35 45 55 65 75 85 95 150 250 350 450 900];\ny = [335 28 37 9 4 3.5 2 1 0.7 0.6 0.5 0.3 0.1 0.01 0.005 0.001];\n% curve fitting\nft = fittype('log(a*x^n + b)','independent','x');\nind_b = strcmp(coeffnames(ft), 'b'); %% index of 'b' coefficient\nlower_values = -inf(1, numel(ind_b)); %% lower value -inf for all coefficients...\nlower_values(ind_b) = 0; %% ...except 0 for b\n[fitresult, gof] = fit(x',log(y)',ft,'Startpoint', [1 -1 1],...\n 'lower',lower_values); %% use 'lower' optional input\n% plots\nhold on\nplot(x,y,'o-')\nplot(x,(fitresult.a .* (x.^fitresult.n)),'-')\nset(gca, 'XScale', 'log', 'YScale', 'log');\n</code></pre>\n"^^ . . . . . "or (2) concatenate the colormaps, and then shift/scale the color data `CData` of the different plot handles to line up with the desired portions of the colormap. A good example (and a link to a Mathworks article about it) can be found in [this answer](https://stackoverflow.com/a/8075772/3460361). (3) Lastly, you could try some helper functions from the file exchange. [`freezeColors`](https://uk.mathworks.com/matlabcentral/fileexchange/7943-freezecolors-unfreezecolors) seems to handle multiple colormap per figure."^^ . . "1"^^ . . . "levenberg marquardt implementation in matlab problem code no converges"^^ . . . . "1"^^ . "Matlab error solving symbolic systems of equations as functions of time"^^ . . . . . . . . "0"^^ . . . "Digital filter coefficients are the z transform of the analog analog filter transfer function, am I wrong?, I wanted the individual coefficients to implement them in an iterative arduino script that allows for real time filtering with little operations. Part of the issue was how I would apply the coefficients properly, specially since every other coefficient was 0 on the numerator side, I'd need the previous 8th , 6th, 4th and 2nd raw values. Or if it should be the previous 4th, 3rd 2nd and 1st. Or maybe the expression "Z-transform" is used for different topics here?"^^ . . "0"^^ . "@confusedcoder please [edit] your question to include details like the required range, and ideally a sketch of the area you expect to be shaded - it's ambiguous which bit you would expect to be shaded over [0,2pi] (since the red circle repeats itself). Can you just treat [pi,2*pi] as independent from [0,pi] and repeat the above code on the 2nd half?"^^ . . . . "0"^^ . "So using simulink, I have a functions set up so they are calculating my required RPM (my x value) based off of how much power I need to pull the plow at the current speed, I also have a function set up to tell me how much wheel torque (my z value) is required to pull the plow at the speed. I do not know how to code it to where I can input my x and z to find y for f(x,y)=z. The top row of the chart is my RPM and the left column is gear, and the value is how much wheel torque is produced with that combination."^^ . "1"^^ . . . "0"^^ . . "Handling Multi-Zone UTM to Lat/Lon/Alt Conversions for Continuous Route Mapping in MATLAB"^^ . . . "file"^^ . . . "0"^^ . . . . . . . . "2"^^ . "<p>In Matlab AppDesigner I want to let the user draw a polyline on a plot. After each click I want to print out the point's coordinate on the command line. However I can't get the callback or event listener for the mouse click to work. Only after the user finished the <code>drawpolyline</code> I can access the coordinates.</p>\n<pre><code>h = drawpolyline('Parent', app.UIAxes,'Color','r');\naddlistener(h,'MovingROI',@app.allevents);\naddlistener(h,'ROIMoved',@app.allevents);\naddlistener(h,'DrawingStarted',@app.allevents);\naddlistener(h,'DrawingFinished',@app.allevents);\naddlistener(h,'AddingWaypoint',@app.allevents);\naddlistener(h,'WaypointAdded',@app.allevents);\naddlistener(h,'VertexAdded',@app.allevents);\naddlistener(h,'DeletingROI',@app.allevents);\naddlistener(h,'ROIClicked',@app.allevents);\naddlistener(h,'RemovingWaypoint',@app.allevents);\naddlistener(h,'WaypointRemoved',@app.allevents);\n\n function results = allevents(app,src,evt)\n evname = evt.EventName;\n switch(evname)\n case{'MovingROI'}\n disp(['ROI moving Previous Position: ' mat2str(evt.PreviousPosition)]);\n disp(['ROI moving Current Position: ' mat2str(evt.CurrentPosition)]);\n case{'ROIMoved'}\n disp(['ROI moved Previous Position: ' mat2str(evt.PreviousPosition)]);\n disp(['ROI moved Current Position: ' mat2str(evt.CurrentPosition)]);\n case{'DrawingStarted'}\n disp('DrawingStarted');\n case{'DrawingFinished'}\n disp('DrawingFinished');\n case{'AddingWaypoint'}\n disp('AddingWaypoint');\n case{'WaypointAdded'}\n disp('WaypointAdded');\n case{'VertexAdded'}\n disp('VertexAdded');\n end\n end\n</code></pre>\n<p>With this code I get only the MovingROI and the MovedROI to work. The rest doesn't work. Also it seems that those listeners are only set-up after the object h of the polyline is created. So it wouldn't work anyway to read-out the point's coordinates after each point is clicked. How could I do this?</p>\n<p><strong>Edit</strong></p>\n<p>I managed to first create the object <code>app.polyline</code> (formerly <code>h</code>) of the polyline, then set up the listeners and only after that let the user start drawing the line. That way the listeners are already active during the drawing. However, only the following events work:</p>\n<pre><code> app.polyline = images.roi.Polyline('Parent',app.UIAxes,'Color','r');\n addlistener(app.polyline,'MovingROI',@app.allevents);\n addlistener(app.polyline,'ROIMoved',@app.allevents);\n addlistener(app.polyline,'DrawingStarted',@app.allevents);\n addlistener(app.polyline,'DrawingFinished',@app.allevents);\n\n addlistener(app.polyline,'AddingVertex',@app.allevents); \n addlistener(app.polyline,'VertexAdded',@app.allevents);\n addlistener(app.polyline,'DeletingVertex',@app.allevents);\n addlistener(app.polyline,'VertexDeleted',@app.allevents);\n addlistener(app.polyline,'DeletingROI',@app.allevents);\n addlistener(app.polyline,'ROIClicked',@app.allevents);\n\n draw(app.polyline);\n</code></pre>\n<p>Of those events, the events 'AddVertex' and 'VertexAdded' only are triggered once the user ads a vertex to an already drawn line. This event doesn't get triggered during a click when the line is first drawn. However I would like to catch the events of those first clicks.</p>\n"^^ . . . . . . "Optimizing two-dimensional interval partitioning for multi-dimensional matrix data"^^ . . "1"^^ . . . . . . . . . . "conditional-statements"^^ . "callback"^^ . . . . . . "Please provide enough code so others can better understand or reproduce the problem."^^ . "0"^^ . . . . . . . "1"^^ . "multidimensional-array"^^ . . "<p>I have a matrix containing label values, say identifying grains, states in made-up maps, etc. The values are in range of thousands.</p>\n<p>The values are unique for homogenoeus region. In case of a map, there is no chance of an exclave etc, but there may be a region with just one neighbour. For example following matrix:</p>\n<pre><code>[a a a c c d\n a a b c c d\n a b b d d d]\n</code></pre>\n<p>I would like to visualize the map but no colormap gives reasonable results - some grain pairs have colours almost matching.</p>\n<p>Is there algorithm to remap the values so there will be no neigbours with a same value but with much lower maximum value? The outcome that looks like some political maps where you have 4 colours that are enough to emphasize the neighbours. For example as follows -</p>\n<pre><code>[1 1 1 3 3 1\n 1 1 2 3 3 1\n 1 2 2 1 1 1]\n</code></pre>\n<p>I have tried meddling with <code>colormap</code> trying <code>lines</code> or randomized, but since the &quot;size&quot; of regions waries a lot it does not produce predictable results.</p>\n"^^ . "Scipy filter coefficients and filtering in MATLAB"^^ . . . "0"^^ . . . "“it seems not possible to create a 4d matrix.” It is possible. And not hard: `cat(4, cell{:})`. But this would be expensive if the matrices are large. It is better to sum the matrices one by one in a loop, then divide by the number of them at the end."^^ . "NONE of the decimal values in pv = 0.01:0.01:0.1 can be represented exactly in IEEE double precision. The actual values in pv are approximations to these decimal numbers. You should not expect to get exact decimal results if you do arithmetic with these kinds of double precision values, so you need to adjust your expectations accordingly and modify your code to account for this. This is not weird behavior, it is expected floating point arithmetic behavior in any computer language, not just MATLAB. You might also explore using the linspace( ) function instead of the colon operator."^^ . . . . "0"^^ . . "Possible duplicate of https://stackoverflow.com/questions/32913301/matlab-date-string-results-in-java-lang-string-in-python-scipy-io, which said that the simplest way to do this is to export the dates as strings and grab them back with usual Python `datetime.datetime` methods.\nTimeStamps are a date format only used by Matlab, according to https://stackoverflow.com/questions/48542674/how-to-read-matlab-datetimes-stored-in-a-file-using-scipy-io-loadmat"^^ . . "confidence-interval"^^ . "0"^^ . "0"^^ . "linear-algebra"^^ . . "<p>Trying to implement compressed sensing with FFT in Matlab. I have implementet compressed sensing for time series with descret cosine transform sucsessfully, but changing dct to fft and idct to ifft is not enough since the code give me only zeros.</p>\n<pre><code>%% Generate signal, DCT of signal\nn = 4000; % points in high resolution signal\nt = linspace(0, 4000, n); \nx = 0.5*cos(2* 0.008 * pi * t) + 0.5*cos(2* 0.016 * pi * t) + 0.5*cos(2* 0.064 * pi * t) + 0.5*cos(2* 0.256 * pi * t); \nxt = fft(x); % Fourier transformed signal\nPSD = abs(real(xt)).^2/((n-1)*1); % Power spectral density\n\n%% Randomly sample signal\np = 128; % num. random samples, p=n/32\nperm = round(rand(p, 1) * n);\ny = x(perm); % compressed measurement\n\n%% Solve compressed sensing problem\nPsi = dct(eye(n, n)); % build Psi\nTheta = Psi(perm, :); % Measure rows of Psi\n\n%s = cosamp(Theta,y',10,1.e-10,10); % CS via matching pursuit\n%% L1-Minimization using CVX\ncvx_begin;\n variable s(n); \n minimize( norm(s,1) ); \n subject to \n Theta*s == y';\ncvx_end;\n\nxrecon = idct(s); % reconstruct full signal\n</code></pre>\n<p>The code work fine with DCT but give zeros when changing basis to FFT.</p>\n<p>Any idea of how to implement FFT here?</p>\n"^^ . . "3"^^ . . "0"^^ . . "1"^^ . "matlab-deployment"^^ . . . . . . "computer-vision"^^ . . . . "I can set it to "Dual Simplex" using `options.Algorithm = "dual-simplex"`but this produces the same result is there a way to set it to Highs? I'm aware i can use use max iterations and i might have to but max time would be an ideal"^^ . "0"^^ . "0"^^ . "1"^^ . . . "One way to obtain those three wrong subplots is if (in your correct code) your input data has only the real component, that is, if your replace `exp(1i *` by `sin(`, or just take `real` of `v_a`, `v_b`, `v_c`; can you verify that you have generated the complex sinusoidal signal?"^^ . . "I would like to create a color scale the matches an image"^^ . "0"^^ . . . . . . . . . . . . . "eigenvalue"^^ . . . . . "0"^^ . . . . "@LuisMendo You are right, that is my bad"^^ . . "0"^^ . "Thanks for the solution @CrisLuengo . It works, even though I don't understand what ```cell{:}``` does. When I stored it in a variable like ```cells=cell{:}``` and I print its size ```size(cells)```, I obtain the size of just one 3d matrix..."^^ . "0"^^ . "<p>I’m working on a project where I convert geographic coordinates (latitude, longitude, altitude) to UTM coordinates (zone, east, north, altitude) for calculating azimuth and elevation. However, I’m facing a significant challenge because my map spans multiple UTM zones, and as points cross these zone boundaries, the UTM coordinates become inconsistent. This creates discontinuities when I try to map a continuous route, especially for longer paths that cover large geographic areas. My workflow involves:</p>\n<pre><code>1. Converting lat, lon, alt to UTM (east, north, zone, altitude).\n2. Performing calculations in UTM coordinates for azimuth and elevation.\n3. Converting the results back to lat, lon, alt to visualize and analyze the path.\n</code></pre>\n<p>The primary issue is handling points across different UTM zones without causing jumps in coordinates due to zone changes. I’ve tried different methods but can’t achieve smooth transitions between zones. I’d appreciate any advice on managing multi-zone UTM conversions in MATLAB, especially if anyone has experience with similar mapping projects or the MATLAB Mapping Toolbox.</p>\n<p>To handle azimuth and elevation calculations accurately for my project, I convert geographic coordinates (latitude, longitude, altitude) to UTM coordinates. The calculations work well within a single UTM zone, but I encounter issues when my points cross zone boundaries. Specifically, the east and north values can change significantly at the boundary, causing discontinuities in what should be a smooth route. My goal is to visualize a continuous path on a map, regardless of zone changes, but the abrupt shifts in UTM coordinates make this difficult.</p>\n<ul>\n<li>I try to direct Lat/Lon Calculations: I attempted to bypass the issue by performing calculations directly on latitude/longitude coordinates instead of UTM. While this avoids zone boundary issues, my azimuth and elevation calculations are less accurate because UTM-based calculations were designed to be more precise for short-distance measurements.</li>\n</ul>\n<pre><code>% List of geographic coordinates (lat, lon) that cross at least two UTM zones\nlatitudes = [40.0, 40.5, 41.0, 41.5, 42.0];\nlongitudes = [-75.0, -74.5, -74.0, -73.5, -73.0];\n\n% Initialize arrays for UTM coordinates and UTM zone names\nutmZones = cell(size(latitudes));\neastings = zeros(size(latitudes));\nnorthings = zeros(size(latitudes));\n\n% Convert geographic coordinates to UTM\nfor i = 1:length(latitudes)\n [eastings(i), northings(i), utmZones{i}] = deg2utm(latitudes(i), longitudes(i));\nend\n\n% Display UTM coordinates and their respective zones\ndisp('UTM Coordinates and Zones:');\ndisp(table(latitudes', longitudes', eastings', northings', utmZones'));\n\n% Plot UTM coordinates with color-coding for different UTM zones\nfigure;\nhold on;\n\n% Define colors for different zones for better visual distinction\ncolors = lines(numel(unique(utmZones))); \n\nfor i = 1:length(latitudes)\n zoneIndex = find(strcmp(utmZones, utmZones{i}));\n scatter(eastings(i), northings(i), 100, 'filled', 'MarkerFaceColor', colors(zoneIndex, :), 'DisplayName', utmZones{i});\nend\n\ntitle('UTM Coordinates Across Multiple Zones');\nxlabel('Easting (m)');\nylabel('Northing (m)');\ngrid on;\nlegend('show');\nhold off;\n\n% Convert UTM back to geographic coordinates\nlatitudes_back = zeros(size(latitudes));\nlongitudes_back = zeros(size(longitudes));\n\nfor i = 1:length(eastings)\n [latitudes_back(i), longitudes_back(i)] = utm2deg(eastings(i), northings(i), utmZones{i});\nend\n\n% Display converted geographic coordinates\ndisp('Converted Back to Geographic Coordinates:');\ndisp(table(latitudes', longitudes', latitudes_back', longitudes_back'));\n\n% Visualize the original and converted back coordinates on a map\nfigure;\nhold on;\nscatter(longitudes, latitudes, 100, 'filled', 'r', 'DisplayName', 'Original Coordinates');\nscatter(longitudes_back, latitudes_back, 100, 'filled', 'b', 'DisplayName', 'Converted Back Coordinates');\ntitle('Comparison of Original and Converted Back Coordinates');\nxlabel('Longitude');\nylabel('Latitude');\nlegend;\ngrid on;\nhold off;\n</code></pre>\n"^^ . "Matlab: Stop execution of one line but continue program execution"^^ . "This is matlab, right? You should tag it."^^ . . . . . "2"^^ . . . . . . . "<p>I have an STL file and I would like to make a binary mask from it in MATLAB, that would be defined similar to this:</p>\n<pre><code>stl_mask = zeros(size(stl_file));\nstl_mask(stl_indices) = 1\n</code></pre>\n<p>I have searched around and there is a <a href="https://es.mathworks.com/matlabcentral/fileexchange/29906-binary-stl-file-reader" rel="nofollow noreferrer"><code>stlread</code> function</a> that lets me visualize the STL file in MATLAB, but I am a bit lost on how to work around it. <a href="https://filetransfer.io/data-package/tA1zp9oi#link" rel="nofollow noreferrer">This is the STL file that I'm using</a>. For the moment, I have just this small code to visualize the STL file:</p>\n<pre><code>clearvars\nfilename = 'example.STL';\n\n[v, f, n, c, stltitle] = stlread(filename);\nfigure;\npatch('Faces',f,'Vertices',v,'FaceVertexCData',c);\n</code></pre>\n"^^ . . "Welcome to Stack Overflow! Can you please [edit] your post to show the, non-working, code you wrote for the DSSS and include the error message in the post? We cannot help you to debug code you haven't shown us, see [mre]."^^ . . . . . "graphics"^^ . . . "Use the debugger. Set a breakpoint in your callback function, then you can see what is going on inside it. https://www.mathworks.com/help/matlab/matlab_prog/debugging-process-and-features.html"^^ . . . . . "symbolic-math"^^ . . "1"^^ . "How do I access a MATLAB UI function in another .m file?"^^ . "0"^^ . . "0"^^ . . "From the [documentation](https://uk.mathworks.com/help/optim/ug/linprog.html#buusznx-options) it looks like the `MaxTime` option only applies if you're using a _Dual-Simplex Algorithm_ (Highs or Legacy). Did you try with one of those set? Otherwise you could approximate how long each iteration is taking and use `MaxIterations` instead, which is applicable to all algos"^^ . "0"^^ . "0"^^ . . . . . "2"^^ . . . . "It can be the case that k_1 ~= k_2. It just happens to not be true for the example I gave. In general I have to assume k_1~= k_2."^^ . . "<p>Seems like you're doing some sort of combination of two distinct things:</p>\n<ol>\n<li>Use a simple function, which can be in its own .m file or one of the methods of your main class:</li>\n</ol>\n<pre><code>% in your initialise class constructor you still have\nbuttonCreate(app);\n</code></pre>\n<pre><code>% In buttonCreate.m\nfunction buttonCreate(app) \n % Create file load 1\n app.fileload1 = uibutton(app.gridLayout, 'push');\n app.fileload1.FontSize = 36;\n app.fileload1.Layout.Row = [8 9];\n % ...\nend\n</code></pre>\n<ol start="2">\n<li>Use a class to hold references to all of your buttons, in which case the objects you create would be properties of that class, rather than the main app object:</li>\n</ol>\n<pre><code>% in your initialise class constructor you create a buttons\n% object and assign it to the buttons property.\n% The buttons don't need to know anything about the app, just\n% the target grid layout to parent the buttons\napp.buttons = buttons( app.gridLayout );\n</code></pre>\n<pre><code>% In buttons.m\nclassdef buttons &lt; handle\n properties\n fileload1\n end\n methods\n function obj = buttons( grid ) \n % Create file load 1\n obj.fileload1 = uibutton(grid, 'push');\n obj.fileload1.FontSize = 36;\n obj.fileload1.Layout.Row = [8 9];\n % ...\n end\n end\nend\n</code></pre>\n"^^ . . . . "histogram"^^ . "1"^^ . "arrays"^^ . "<p>You are just missing 3rd parameter for printing. And use for loop for simplicity. Please check the below code.</p>\n<pre><code>for k=1:length(num2)\nfprintf ('%2.0f x %2.0f = %3.0f \\n',num1, table(1,k),table(2,k));\nend\n</code></pre>\n"^^ . "1"^^ . "I didn't think of this! Thank you."^^ . "0"^^ . "0"^^ . . . . . "0"^^ . "1"^^ . . "0"^^ . . "fmincon Biasing one ouput and minimizing the objective Function"^^ . "How to pass matrix as input to matlab function from .net app?"^^ . . "<p>Your matrix A is singular. The MATLAB doc states that in these cases, mldivide is unreliable (&quot;... When working with ill-conditioned matrices, an unreliable solution can result ...&quot;) and suggests to use lsqminnorm( ) or pinv( ) instead (see &quot;Tips&quot;). E.g.,</p>\n<pre><code>&gt;&gt; A = [ -1 0 0;\n 1 1 -1;\n 0 -1 1 ];\n&gt;&gt; B = [-1; 0; 1];\n&gt;&gt; A\\B\nWarning: Matrix is singular to working precision. \n \nans =\n NaN\n NaN\n NaN\n&gt;&gt; A*ans-B\nans =\n NaN\n NaN\n NaN\n&gt;&gt; lsqminnorm(A,B)\nans =\n 1.0000\n -0.5000\n 0.5000\n&gt;&gt; A*ans-B\nans =\n 1.0e-15 *\n 0.4441\n -0.3331\n -0.1110\n&gt;&gt; pinv(A)*B\nans =\n 1.0000\n -0.5000\n 0.5000\n&gt;&gt; A*ans-B\nans =\n 1.0e-15 *\n 0.2220\n -0.4441\n 0.2220\n</code></pre>\n"^^ . . . . . "<p>I implemented a first draft of the Adams-Bashforth multistep-solver in C++. To make this method work, you need coefficients. In Wikipedia these are the <code>bj</code> in this formula:</p>\n<pre><code>y_n+1 = y_n + h * sum_over_j(bj * f(t_n-j, y_n-j))\n</code></pre>\n<p>I couldn't find any tables online that go beyond order 6 for these coefficients, so I tried calculating them myself with this Matlab script:</p>\n<pre><code> function bj = adamsBashforthCoefficients(order)\n h = 1;\n\n nodes = -(0:(order-1));\n\n bj = zeros(1, order);\n \n for j = 1:order\n L = @(x) arrayfun(@(xi) prod((xi - nodes([1:j-1, j+1:end])) ./ (nodes(j) - nodes([1:j-1, j+1:end]))), x);\n \n% bj(j) = integral(L, 0, 1) / h;\n bj(j) = integral(L, 0, 1, 'AbsTol', 1e-12, 'RelTol', 1e-12) / h; % Test if tolerances were to high - they weren't\n\n end\n end\n</code></pre>\n<p>Up to order 6 this gives the same values as found online, so I assumed they are correct. However: Up to order 6 Adams-Bashforth seems to work fine, but order 7 or higher give frequent instabilities. Meaning: Some variables explode to huge values.</p>\n<p>Can higher orders in Adams-Bashforth create instabilities where lower orders work? Should that already happen at order 7 (Matlabs ode113 goes up to order 11 or 12)? Or do I simply have the wrong coefficients?</p>\n<p>If the coefficients are wrong, I would greatly appreciate it, if somebody could show me code how to calculate them correctly or simply point me to a table that goes to higher orders (at least 11-12). For comparison: Here is, what my script calculated for orders 6-8:</p>\n<pre><code> // Order 6\n{ 2.970138888888889, -5.502083333333333, 6.931944444444445, -5.068055555555556, 1.997916666666667, -0.329861111111111 }\n\n // Order 7\n{ 3.285730820105820, -7.395634920634921, 11.665823412698412, -11.379894179894180, 6.731795634920635, -2.223412698412698, 0.315591931216931 }\n\n // Order 8\n{ 3.589955357142857, -9.525206679894177, 18.054538690476193, -22.027752976190477, 17.379654431216931, -8.612127976190475, 2.445163690476190, -0.304224537037037 }\n</code></pre>\n"^^ . . . . "3"^^ . "@Argyll Noted it. I hope I understood the flaws of my question correctly and made the right corrections to it for a better understanding of what is happening in my code for a better understanding of the problem."^^ . . . . "0"^^ . . "<p>I want to calculate the eigenvalues of the (discrete) Laplace operator in 3D. For this I want to use the matlab command <code>eigs</code>. I have implemented the Laplace operator as a function as it is recommended in the documentation of <code>eigs</code>. For this it is necessary to design the function, such that it takes one array (1D) as an input and gives one array (1D) as an output.\nPlease note, that I know, that the spectrum of the (discrete) Laplacian is known analytically. My actual problem goes beyond and I tried to minimize my actual issue to the question you read in this post. In other words: I would like to use the function together with <code>eigs</code> in any case.</p>\n<p>Here I define my function:</p>\n<pre><code>function Lap = Laplace(f,Lx,Ly,Lz,Nx,Ny,Nz);\n\nkx(1:Nx/2)=(0:Nx/2-1)*2*pi/Lx; %Calculate the momentum vector in x-direction\nkx(Nx/2+1:Nx)=(-Nx/2:-1)*2*pi/Lx;\n\nky(1:Ny/2)=(0:Ny/2-1)*2*pi/Ly; %Calculate the momentum vector in y-direction\nky(Ny/2+1:Ny)=(-Ny/2:-1)*2*pi/Ly;\n\nkz(1:Nz/2)=(0:Nz/2-1)*2*pi/Lz; %Calculate the momentum vector in z-direction\nkz(Nz/2+1:Nz)=(-Nz/2:-1)*2*pi/Lz;\n\n[Kx,Ky,Kz]=meshgrid(kx,ky,kz); %Calculate a grid in the k-space\n\nK=sqrt(Kx.*Kx+Ky.*Ky+Kz.*Kz); %Calculate at every grid-point the absolute value of the k-vector\n\nf3D = reshape(f,[Nx,Ny,Nz]); %reshape the input vector in order to multiply grid-point by grid point with K\n\nLap3D = ifftn(K.*K.*fftn(f3D)); %Action of the Laplacian \n\nLap = Lap3D(:); %Reshape back to 1D-format\nend\n</code></pre>\n<p>And then I run the command:</p>\n<pre><code>Lx=1; %length in x-direction\nLy=1; %length in y-direction\nLz=1; %length in z-direction\nNx=128; %number of points in x-direction\nNy=128; %number of points in y-direction\nNz=128; %number of points in z-direction\n\nAfun= @(x) Laplace(x,Lx,Ly,Lz,Nx,Ny,Nz);\n\ntic\neigs(Afun,Nx*Ny*Nz,12,'smallestabs','Tolerance',1e-9 ,'Display',1,'SubspaceDimension',100)\ntoc\n</code></pre>\n<p>As I result I should get the 12 smallest eigenvalues, but when I run the code it produces the following output:</p>\n<pre class="lang-none prettyprint-override"><code>\n 1.0e-05 *\n\n 0.206138475834832\n 0.208291225315224\n 0.208291225315224\n 0.208291225315224\n 0.208291225315225\n 0.210454435947029\n 0.210454435947030\n 0.210454435947030\n 0.210489412585876\n 0.210489412585876\n 0.210489412585877\n 0.212627347524422\n</code></pre>\n<p>This result seems wrong. It looks like the eigenvalues are shifted. I do not see my mistake. Thanks for any kind of help.</p>\n"^^ . . "@beaker Unfortunatelly the "data" are not in the form of a graph-representing matrix. On the other hand, naming the problem behind helps a lot."^^ . . . "Thanks @LuisMendo and AnderBiguri I don't have symbolic toolbox license and finally used [Mutiprecision Computing Toolbox](https://www.advanpix.com/) do to the test (NB: It is no free after trial but extremely fast and solve my precision issue in recurrence). Regarding link digits/bits correspondance, looking at how [floating points](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) encoding the relation is `digits = (bits - bitsReserverExponent)*log10(2)` , so almost 34 digits for quadrule-precision (128bits)"^^ . . . "1"^^ . "1"^^ . "2"^^ . . "0"^^ . . "1"^^ . . . . . . . "2"^^ . . "0"^^ . "0"^^ . "1"^^ . "c++"^^ . . "1"^^ . . "0"^^ . . . . "0"^^ . "matlab-app-designer"^^ . "<p>You can use the linear indices returned by <code>unique</code> to give you the column number of each unique integer. Since the integers are given in sorted order by default, the list of indices (converted to column numbers) gives one column of the output.</p>\n<p>Given:</p>\n<pre class="lang-matlab prettyprint-override"><code>A=[ 1 10 9\n 1 2 4\n 3 2 11\n 3 12 5\n 6 13 4\n 6 7 15\n 8 7 5\n 8 14 16]\n</code></pre>\n<p>Find the indices of the first occurrence of each integer:</p>\n<pre class="lang-matlab prettyprint-override"><code>[Y,I] = unique(A); % Y is not necessary, only there for verification\ndisp([Y,I]);\n\n 1 1\n 2 10\n 3 3\n 4 18\n 5 20\n 6 5\n 7 14\n 8 7\n 9 17\n 10 9\n 11 19\n 12 12\n 13 13\n 14 16\n 15 22\n 16 24\n</code></pre>\n<p>(Note that if we were <strong>not</strong> guaranteed to have each integer appear at least once, we could use <code>Y</code> as a row index into the result array.)</p>\n<p>The linear indices can then be converted to (row and) column numbers using <code>ind2sub</code>:</p>\n<pre class="lang-matlab prettyprint-override"><code>[~,C] = ind2sub(size(A),I)\nC =\n\n 1\n 2\n 1\n 3\n 3\n 1\n 2\n 1\n 3\n 2\n 3\n 2\n 2\n 2\n 3\n 3\n</code></pre>\n<p>If both occurrences of an integer are guaranteed to be in the same column, we're done:</p>\n<pre class="lang-matlab prettyprint-override"><code>Q = [C, C];\n</code></pre>\n<p>If occurrences of an integer can be in <strong>different</strong> columns, we'll just use <code>unique</code> a second time:</p>\n<pre class="lang-matlab prettyprint-override"><code>B = A;\nB(4,[2,3]) = B(4,[3,2])\nB =\n\n 1 10 9\n 1 2 4\n 3 2 11\n 3 5 12 &lt;-- 12 and 5 swapped\n 6 13 4\n 6 7 15\n 8 7 5\n 8 14 16\n\n[~,I] = unique(B, &quot;first&quot;);\n[~,C] = ind2sub(size(B),I);\nQ(:,1) = C;\n[~,I] = unique(B, &quot;last&quot;);\n[~,C] = ind2sub(size(B),I);\nQ(:,2) = C;\ndisp(Q);\n\n 1 1\n 2 2\n 1 1\n 3 3\n 2 3 &lt;-- 5's are in different columns\n 1 1\n 2 2\n 1 1\n 3 3\n 2 2\n 3 3\n 3 3 &lt;-- 12 is only in 1 column\n 2 2\n 2 2\n 3 3\n 3 3\n</code></pre>\n"^^ . . . . . . "0"^^ . . . . . "@LutzLehmann Indeed: Further tests revealed, that it depends on the step-size wether or not orders above 6 are stable. At a bit smaller step-sizes higher orders were stable, so my coefficients are correct I think. Do you think it makes sense to use Adams-Moulton (with the next timestep estimated by Adams-Bashforth) to increase stability? My ODE-function is very expensive, so the usual 2 evaluations with Adams-Bashforth-Moulton are inefficient (compared to one eval with Adams-Bashforth). But I also could just interpolate y_(n+1) at first. Do you think, this would be precise enough?"^^ . . . "You’re computing `condition = (pres-1)*3 + stimulus`. Just write a loop to set those values."^^ . "<p>I have a recursive computation code of mine (containing only simple <code>+</code>, <code>*</code>, <code>exp</code>, <code>etc</code> arithmetic on complex valuated numbers) that starts to loose precision when increasing the depth of iterations and I was willing to see if using quadruple-precision (or higher) numbers would help.</p>\n<p>For this I was willing to try following toolboxes:</p>\n<ul>\n<li><a href="https://www.mathworks.com/matlabcentral/fileexchange/36534-hpf-a-big-decimal-class" rel="nofollow noreferrer">HPF</a></li>\n<li><a href="https://www.mathworks.com/matlabcentral/fileexchange/6446-multiple-precision-toolbox-for-matlab" rel="nofollow noreferrer">MPT</a></li>\n</ul>\n<p>But I'm a bit confused about how to use them because <code>precision</code> is to be provided as a number of digits after comma and I don't see from examples how this relates to quantities being stored/manipulated as 64/128 bits values.</p>\n<p>Can you show me some quick example to create quadruple-precision (i.e. 128 bits) with those toolboxes and explain relation with <code>precision</code> as number of digits as expected as argument in those toolboxes ?</p>\n"^^ . . "1"^^ . . . . . . "0"^^ . "0"^^ . . "0"^^ . . "0"^^ . . . "0"^^ . . . "<p>I have a 1x12 cell in Matlab and each element of this cell has a 3d matrix. I want to make the mean of these 3d matrices, so that I obtain a 3d matrix that has the same dimensions of each one of the 3d matrices of the cell and that is the mean of the 12 3d matrices. How can I do this operation ?</p>\n<p>I tried to extract each cell and create a 4d matrix so that I could do <code>mean(fourdmatrix,4)</code> . However, it seems not possible to create a 4d matrix.</p>\n<p>Ideed, a code like this:</p>\n<pre><code>cell={threedmatrixA, threedmatrixB, ...}\nfourdmatrix=[];\n\nfor i=1:12\n fourdmatrix(i)=cell{i};\nend\n</code></pre>\n<p>does not work. How can I do it ?</p>\n"^^ . "By the way, Argyll didn’t complain about not understanding the code, he complained that it is not *mimimal*. There’s a lot of redundant stuff happening in the code that is not necessary to understand the problem. This in turn makes things harder to understand, we have to do more work to read and understand all of that code and look for the relevant bits. You should always try to make code as concise as possible for the purpose of asking others for help with it. Minimal, but complete, so that we can copy-paste and run it ourselves. Please read the text at the link Argyll posted."^^ . . "2"^^ . . . . . . . . . "0"^^ . "Hey Cris,\n\nThanks for your reply ! \nI really like your second idea, I'll try this out.\n\nMaybe another possibility could be to create my own subclass of the python list or tuple, which is transparent to method calls (transmitts unknown method calls to the list or tuple's elements' instances like in Matlab). \nI could achiege this using a decorator of some sort, and use that one instead of the default python list or tuple in my code...\n\nLike you said, there are many variants. \nThanks again !"^^ . . . . . . . . . "0"^^ . . . . . "contour"^^ . . . . . "1"^^ . . "0"^^ . "excel"^^ . "wireless"^^ . "ode45"^^ . . . . "1"^^ . . . . "binary"^^ . . "Difference in Cholesky Decomposition Results Between Julia and MATLAB"^^ . . . "0"^^ . "http"^^ . "psd"^^ . "4"^^ . "<p>The error in me not being able to recreate the waveforms like in those subplots was that i was only adding the real part of the complex sinosuidal waveform .</p>\n<p>In order for me to extract the waveform I used &quot;PLL block&quot; (to get the frequency 'f') and clock (to get the time values) .</p>\n<p>Then the code goes as follows.</p>\n<pre><code>function [va_pos,vb_pos,vc_pos,va_neg,vb_neg, vc_neg, va_zero,vb_zero,vc_zero,va_reconstructed,vb_reconstructed,vc_reconstructed] = fcn(t, f, va_in, vb_in, vc_in)\n\n% Calculate the phase-shifted voltages\nv_a = va_in * exp(1i * (2 * pi * f * t)); % V_a = A * e^(j * 0)\nv_b = vb_in * exp(1i * (2 * pi * f * t - 2 * pi / 3)); % V_b = A * e^(j * 120°)\nv_c = vc_in * exp(1i * (2 * pi * f * t + 2 * pi / 3)); % V_c = A * e^(j * -120°)\n\n% Define complex exponential for 120 degrees and 240 degrees\nalpha = exp(1i * 2 * pi / 3); % e^(j * 120 degrees)\nalpha_square = exp(-1i * 2 * pi / 3); % e^(j * 240 degrees)\n\n% Calculate positive sequence component (full complex value)\nva_pos = (1/3) * (v_a + alpha * v_b + alpha_square * v_c);\nvb_pos = alpha_square * va_pos;\nvc_pos = alpha * va_pos;\n\n% Calculate negative sequence component (full complex value)\nva_neg = (1/3) * (v_a + alpha_square * v_b + alpha * v_c);\nvb_neg = alpha * va_neg;\nvc_neg = alpha_square * va_neg;\n\n% Calculate zero sequence component (real part)\nva_zero = (1/3) * (v_a + v_b + v_c);\nvb_zero = va_zero;\nvc_zero = va_zero;\n\n% Reconstruct the original signal (optional)\n% This can be done to check if va_in ≈ va_pos + va_neg + va_zero\nva_reconstructed = va_pos + va_neg + va_zero;\nvb_reconstructed = vb_pos + vb_neg + vb_zero;\nvc_reconstructed = vc_pos + vc_neg + vc_zero;\n</code></pre>\n<p>end</p>\n<p>Now after you reconstruct . For plotting the real time values you can plot using real() in time domain.</p>\n<p>I was plotting using real and then reconstrucing using the real part as well (That was the error) .</p>\n<p>Thank you for the help .</p>\n"^^ . . . "Start with a smaller matrix, see what kind of differences you see. Look at the numeric values, you'll be able to answer your question of "Could this be due to numerical precision differences?"."^^ . . "indexing"^^ . . . "1"^^ . . . . . . . . "1"^^ . . . . "1"^^ . . "0"^^ . . . . . "0"^^ . "0"^^ . . "0"^^ . "2"^^ . "0"^^ . . "1"^^ . . . "0"^^ . . "<p>Environment:\nMatlab R2022b\nSimulink model</p>\n<p>Problem:\nI was generating code from Embedded coder and generated codes have header file declaration present in the C file instead of H file. I used the same model in another computer with R2020b (after exporting to previous version), and same model generated the # includes in H file.</p>\n"^^ . . . . . "0"^^ . . . . "I think you're looking for "graph coloring", but unfortunately I see no built-in implementation in MATLAB. I did find an implementation in File Exchange, but I haven't used it and don't know how good it is."^^ . . . "structure"^^ . "2"^^ . "<p>I have created a script in Matlab that processes several data channels into figures and produces a Word doc and PDF filled with the figures pasted into it. This produces a fairly large word document with several different sections. I am using the Word COM through the actxserver function to create this document. In it I set up a table of contents using the following 4 lines:</p>\n<p><code>rang = word.ActiveDocument.Range(0, 0);</code><br />\n<code>word.ActiveDocument.TablesOfContents.Add(rang);</code><br />\n<code>word.ActiveDocument.TablesOfContents.Format = 0;</code><br />\n<code>word.ActiveDocument.TablesOfContents.Item(1).Update;</code></p>\n<p>This produces a suitable table of contents, however, I also want this table of contents to act as internal hyperlinks to there respective sections. I have spent quite a while on this and have found several possible methods that didn't work. Has anyone tried to do something like this before and managed to get the hyperlinks working in the generated Word Doc and (if possible in the PDF saved from the Word Doc.</p>\n<p>Any help will be appreciated</p>\n<p><code>word.ActiveDocument.TablesOfContents.UseHyperlinks = true;</code></p>\n<p>I expected this to work because as far as I can find this is the documented command.</p>\n"^^ . . . "1"^^ . "Fast computation of 2D-convolution using "kernel" in fourier space"^^ . "0"^^ . . "0"^^ . . . . . "0"^^ . . . "Incrementing an extra step in MATLAB loop yields incorrect values?"^^ . . "0"^^ . "<pre><code>function cikti = sigmoidDerivative(x)\ncikti = sigmoid(x) .* (1 - sigmoid(x));\n</code></pre>\n<p>This code part has to be changed to</p>\n<pre><code>function cikti = sigmoidDerivative(x)\ncikti = x .* (1 - x);\n</code></pre>\n<p>because in the Jacobean function, the &quot;sigmodiDerivative()&quot; funtion is called with parameter that already calculated with sigmoid() function</p>\n<pre><code>[~ , jA1] = forward_pass(jinput_vals(i),W1,b1,W2,b2);\n derivW1 = -1 * W2'.* sigmoidDerivative(jA1) *jinput_vals(i); \n</code></pre>\n<p>&quot;jA1&quot; is already return from the &quot;sigmoid()&quot; function and so repeated unnecessary sudden increase and decrease of lamba problem solved.</p>\n"^^ . "1"^^ . "optimization"^^ . . . . "matplotlib"^^ . . . . . "0"^^ . . "@Irreducible Hello, thank you very much for the comment. How would you load them directly onto matlab? I tried using thos SOS structure but it's just the same array?\nI'll check out the fvtool, thank you very much again."^^ . "0"^^ . "<p>There is a group of excel files (10 files), in each of which there is a table: 2 columns (the name of the parameter, its value) and 12 rows (the number of parameters and, accordingly, their values). It is necessary to calculate the average between 10 variations of a single parameter. There is a program for this below. However, I noticed that he performs the calculation with an error of one ten-thousandth of a number, he underestimates it. For example, here's what the result gives me:</p>\n<div class="s-table-container"><table class="s-table">\n<thead>\n<tr>\n<th>Matlab</th>\n<th>Averaging using Excel</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0.0288</td>\n<td>0,02891568</td>\n</tr>\n<tr>\n<td>0.0008</td>\n<td>0,000836121</td>\n</tr>\n<tr>\n<td>0.0012</td>\n<td>0,00117159</td>\n</tr>\n<tr>\n<td>0.0723</td>\n<td>0,07248086</td>\n</tr>\n<tr>\n<td>0.0858</td>\n<td>0,085798107</td>\n</tr>\n<tr>\n<td>0.0867</td>\n<td>0,086977032</td>\n</tr>\n<tr>\n<td>0.1030</td>\n<td>0,102957729</td>\n</tr>\n<tr>\n<td>0.9524</td>\n<td>0,959947104</td>\n</tr>\n<tr>\n<td>-0.0050</td>\n<td>-0,005002288</td>\n</tr>\n<tr>\n<td>0.0008</td>\n<td>0,000837283</td>\n</tr>\n<tr>\n<td>-0.0000</td>\n<td>-1,28168E-05</td>\n</tr>\n<tr>\n<td>0.0000</td>\n<td>2,17761E-06</td>\n</tr>\n</tbody>\n</table></div>\n<pre><code>clc, clear;\n \n% Folder with Excel files\nfolder = 'The path to the folder with 10 excel files'; % the path to the folder\nfiles = dir(fullfile(folder, '*.xlsx')); % we get a list of all excel files\n \n% Initialize the vector to store the average values\naverage_values = [];\n \n% Loop through all files\nfor i = 1:length(files)\n % The full path to the file\n file_path = fullfile(folder, files(i).name);\n \n % Reading data from an Excel file\n opts = detectImportOptions(file_path, 'VariableNamingRule', 'preserve'); \n data = readtable(file_path, opts);\n \n % Check if there is at least one numeric column\n if any(varfun(@isnumeric, data, 'OutputFormat', 'uniform'))\n % We extract only numeric data\n numeric_data = data{:, varfun(@isnumeric, data, 'OutputFormat', 'uniform')}; \n \n % We calculate the average values for the rows, ignoring NaN\n avg_values_per_row = mean(numeric_data, 2, 'omitnan');\n \n % Saving the average values in an array\n average_values = avg_values_per_row;\n else\n warning('There are no numeric columns in the &quot;%s&quot; file.', files(i).name);\n end\nend\n \n% Displaying average values\ndisp('Average values by line:');\ndisp(average_values);\n \n% Displaying the number of rows\ndisp('Number of lines:');\ndisp(length(average_values));\n</code></pre>\n<p>As you can see, for parameters number 1, 4, 6, 8, the underestimation goes from 0.0001 to 0.0007 units (in the case of the 8th parameter, the underestimation is already in one thousandth of the number). What is most interesting is that if you manually enter 10 values of each parameter into the <code>mean</code> function in Matlab and calculate, it will give the correct result without this underestimation (using the example of the 8th parameter):</p>\n<pre><code>&gt;&gt; mean([0.952380002 0.980380905 0.97087088 0.95237715 0.952379051 0.970871364 0.980383351 0.925921306 0.961536062 0.952370972\n])\n\nans =\n\n 0.9599\n</code></pre>\n<p>Where can there be a problem in the code and how to fix it so that it gives an accurate result? (the attachment contains a folder with files from the example: <a href="https://drive.google.com/file/d/1COPpBq2mU8Ww62DRvbOKTtr_aC-LsCIL/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1COPpBq2mU8Ww62DRvbOKTtr_aC-LsCIL/view?usp=sharing</a>)</p>\n"^^ . . "1"^^ . . . . "I want to plot a semi-random graph in Matlab"^^ . . "How to implement attenuation into a Bluetooth Mesh MATLAB script?"^^ . . . . . . . "<p>I would require wrapping the logic of my Simulink model to be obfuscated or hidden. One of the ways to perform it is to create a similar s-function block with the object code generated from the same Simulink block. I am facing difficulty in realizing this programmatically. Is there a way around to realize them programmatically or rely on GUI to create manually.</p>\n"^^ . . "Right, but the entire point of chaos theory is that you can say mathematically whatever you want, in practice you will never be able to simulate it. At some point you need a tolerance of 1e-(e^100000000000)), so its meaningless to try to do it. Note that the same question can be applied to any differential equation, but _some_ differential equations will give you the same answer I gave you, while others are easily solvable numerically. I don't know if its knowable how to scale the tolerances (which is why I didn't answer the question) but even if its possible, it would be at least exponential."^^ . . . . "0"^^ . "there's a matlab function called estimatetrf, if i'm not mistaken"^^ . "<p>I want to numerically evaluate the following integral:</p>\n<p><img src="https://i.sstatic.net/8MxID0ST.png" alt="integral" /></p>\n<p>If the function f is given in discrete form on a grid, I want to be able to very efficiently compute the integral. The idea is to understand it as a multiplication in the Fourier space and use FFT:</p>\n<p><img src="https://i.sstatic.net/EjiEGVZP.png" alt="fourier" /></p>\n<p>if xi and eta are the Fourier variables. I tried to implement this in Matlab, but dont get exact results (probably because I dont quite understand the FFT).</p>\n<p>I have the following minimal working example in Matlab:</p>\n<pre><code>N = 101;\nx = linspace(-1, 1, N); hx = x(2)-x(1);\n[X, Y] = meshgrid(x, x);\n\na = 1/2;\nf = 2/pi*a*real(sqrt(1-(X.^2+Y.^2)/a^2));\nf_pad = zeros(2*N, 2*N); f_pad(1:N, 1:N) = f;\n\nk = linspace(0, pi/hx, N+1); k = [k k(end-1:-1:2)]; hk = k(3)-k(2);\n[KX, KY] = meshgrid(k, k);\nK = sqrt(KX.^2 + KY.^2);\n\nchess = mod((1:2*N)+(1:2*N)',2); chess = -chess; chess(chess==0) = 1;\n\nG = 1./K;\nG(1,1) = 4*integral2(@(x,y) 1./(sqrt(x.^2+y.^2)),0,0.5*hk,0,0.5*hk)/hk^2;\n\nR = ifft2(G.*2.*chess.*fft2(f_pad), 'symmetric'); \nR = R(N+1:end, N+1:end);\n\nRana = (a^2-x.^2/2) .* (abs(x)&lt;=a) + ...\n real(a^2/pi*((2-x.^2/a^2).*asin(a./abs(x))+sqrt(x.^2-a^2)/a)) .* (abs(x)&gt;a);\n\nplot(Rana);\nhold on;\nplot(R((N-1)/2+1,:));\n</code></pre>\n<p>R is the result of the integral, f is the input function and G is the fraction in the Fourier-space; the singularity at xi = 0 and eta = 0 of G is dealt with by taking the average value of the function in the surroundings of the point.\nI compare the final result to an analytical solution, which in this case exists. But it doesn't match perfectly (and doesn't get better, when I increase N? Why is that? And I also don't understand why the chess-matrix is necessary (I copied it from an example I found)?</p>\n"^^ . . . . "0"^^ . . "1"^^ . . . . "0"^^ . . . . "0"^^ . . "1"^^ . "3"^^ . . "0"^^ . . . "<p>Matlab has object arrays, Python has lists or tuples.\nCalling a method of a class on an object array of objects of that class, is easy in Matlab:</p>\n<pre><code>A = [Class1(1), Class1(2)];\n\nB = A.toClass2();\n</code></pre>\n<p>see &quot;Invoking Methods on an Object Array&quot; <a href="https://ch.mathworks.com/help/matlab/matlab_oop/accessing_properites_and_methods_in_object_arrays.html" rel="nofollow noreferrer">here</a></p>\n<p>In Python, this would not be 1 to 1 transferable because on the second line, the interpreter would look for the method toClass2() in the List class, which it will not find (-&gt;error).</p>\n<p>I found out that this can be solved from outside that method's definition, on the user side, by calling it in a for loop, list comprehension, map of a function or lambda function, or even using numpy.vectorize(), see <a href="https://stackoverflow.com/questions/2682012/how-to-call-same-method-for-a-list-of-objects">this</a>.\nEach of these solutions imply heavier syntax on the user side, and one thing still misses; what if I want the method Class1.toClass2() can decide for itself how to treat a list of multiple objects received as input.\nFor instance a method Class1.Sum() would logically sum all elements on which it is applied and return a single object, whereas another doing some transformation like Class1.toClass2() might as well return an array of new objects.</p>\n<p>Alternatively, one can make the method toClass2() also accept a List as self input, and call it explicitly on the second line on the list A using:</p>\n<pre><code>B = Class1.toClass2(A) \n</code></pre>\n<p>This allows methods choosing how to treat List inputs, but generates slightly heavier syntax on the user's side.</p>\n<p>Does anyone see another solution ?\nMaybe there is one using method decorators, class decorators, or even subclassing the List class ..</p>\n<p>Else more generally, how to adapt this OOP software architecture design thinking from Matlab arrays to Python's universe ?</p>\n"^^ . . . "<pre><code>N = 101;\nx = linspace(-1, 1, N); hx = x(2)-x(1);\ny = linspace(-1, 1, N); hy = y(2)-y(1);\n[X, Y] = meshgrid(x, x);\n\na = 1/2;\nF1 = 2/pi*a*real(sqrt(1-(X.^2+Y.^2)/a^2)); % f(x,y)\n</code></pre>\n<p>this is <code>f(x,y)</code> with <code>a=.5</code></p>\n<pre><code>figure(1)\nhs=surf(X,Y,F1)\nhs.EdgeColor='none';\n</code></pre>\n<p><a href="https://i.sstatic.net/IxT4xwbW.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IxT4xwbW.jpg" alt="enter image description here" /></a></p>\n<p>And <code>f1</code> is the integrant, the actual function to integrate 2D</p>\n<pre><code>f1 = @(x_,y_) 2/pi*a*real(sqrt(1-(x_.^2+y_.^2)/a^2))\n</code></pre>\n<p>Setting <code>x=.5;y=.5;</code> as parameters.</p>\n<pre><code>x0=.5;y0=.5;\nF2=@(x1,y1) f1(x1,y1)./((x0-x1).^2+(y0-y1).^2).^.5; \n\nZ=integral2(F2,x(1),x(end),y(1),y(end));\n</code></pre>\n<p>resulting in</p>\n<pre><code>Warning: Reached the maximum number of function evaluations\n(10000). The result fails the global error test. \n&gt; In integral2Calc&gt;integral2t (line 129)\nIn integral2Calc (line 9)\nIn integral2 (line 105)\nIn double_integral_example (line 23) \nWarning: Reached the limit on the maximum number of intervals\nin use. Approximate bound on error is 1.6e-15. The integral\nmay not exist, or it may be difficult to approximate\nnumerically to the requested accuracy. \n&gt; In integralCalc/iterateScalarValued (line 372)\nIn integralCalc/vadapt (line 132)\nIn integralCalc (line 75)\nIn integral2Calc&gt;@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions) (line 17)\nIn integral2Calc&gt;@(x)arrayfun(@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions),x,ymin(x),ymax(x)) (line 17)\nIn integralCalc/iterateScalarValued (line 323)\nIn integralCalc/vadapt (line 132)\nIn integralCalc (line 75)\nIn integral2Calc&gt;integral2i (line 20)\nIn integral2Calc (line 7)\nIn integral2 (line 105)\nIn double_integral_example (line 26) \nWarning: The integration was unsuccessful. \n&gt; In integral2 (line 108)\nIn double_integral_example (line 26) \n</code></pre>\n<p>function <code>integral2</code> needs some fields changed from default to return a result</p>\n<pre><code>Z=integral2(F2,x(1),x(end),y(1),y(end),'Method','iterated','AbsTol',0,'RelTol',1e-10)\n\nZ =\n NaN\n</code></pre>\n<p>too strict</p>\n<pre><code>Z=integral2(F2,x(1),x(end),y(1),y(end),'Method','iterated','AbsTol',1e-5,'RelTol',1e-8)\n \n Z =\n 0.250008992645364\n</code></pre>\n<p>Now it works</p>\n<p>I am submitting the above lines as answer while one of my machines is busy calculating the following</p>\n<pre><code>F3=zeros(N,N);\n\nfor k1=1:1:numel(x)\n for k2=1:1:numel(y)\n \n x0=x(k1);y0=y(k2);\n F2=@(x1,y1) f1(x1,y1)./((x0-x1).^2+(y0-y1).^2).^.5; \n \n F3(k1,k2)=integral2(F2,x(1),x(end),y(1),y(end),'Method','iterated','AbsTol',1e-5,'RelTol',1e-8);\n \n end\nend\n\nfigure(2)\nhs3=surf(X,Y,F3)\n</code></pre>\n<p><a href="https://i.sstatic.net/Gsw2LzyQ.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Gsw2LzyQ.jpg" alt="enter image description here" /></a></p>\n<p>The narrow gap is again MATLAB getting results but error out of specs.</p>\n<p><a href="https://i.sstatic.net/AJJJ1Oo8.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AJJJ1Oo8.jpg" alt="enter image description here" /></a></p>\n<p><strong>Comment:</strong></p>\n<p>Double loop on <code>integral2</code> is not time efficient for <code>N&gt;10</code> , at least for the machine I used to answer this question.</p>\n<p>There are other ways to get a result for large N but since</p>\n<p>understand that would be another question, on how to optimize an already working solution to the above question.</p>\n"^^ . . . . . . "This is what the FFT computes: https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Definition — it uses k=0..N-1 as frequencies. But you can assign frequencies however you want, it’s just about how you interpret the maths. Note how the DFT does not consider a sampling frequency, it just has N input samples and produces N output frequencies. There is no specific values associated to the X axis (sample locations) of either input or output."^^ . . . "1"^^ . . "<p>In MATLAB - We explicitly defining the number of segments through the window size and overlap.</p>\n<pre><code>spectrogram(x, windowSize, overlap, nfft, Fs, 'yaxis');\n</code></pre>\n<p>While in python - the number of segments is determined by the length of the input signal and the NFFT parameter</p>\n<p>By keeping this as reference...we need to adjust the input signal length and the NFFT parameter.</p>\n<pre><code>Fs = 50 * 10**6 \nN = 500 \ndesired_segments = 500 \n</code></pre>\n<p>and</p>\n<pre><code>f, t, Sxx = signal.spectrogram(x, fs=Fs, nperseg=N, noverlap=0, nfft=N, \n return_onesided=False, scaling='density')\n</code></pre>\n<p>Final code</p>\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\n\n\nFs = 50 * 10**6 \nN = 500 \ndesired_segments = 500 \n\n\nt = np.linspace(0, 1, Fs, endpoint=False)\nx = np.sin(2*np.pi*1e6*t) + 0.5*np.sin(2*np.pi*2e6*t)\n\n\nsignal_length = N * desired_segments\n\n\nif len(x) &gt; signal_length:\n x = x[:signal_length]\nelse:\n x = np.pad(x, (0, signal_length - len(x)), mode='constant')\n\n\nf, t, Sxx = signal.spectrogram(x, fs=Fs, nperseg=N, noverlap=0, nfft=N, \n return_onesided=False, scaling='density')\n\n\nSxx = np.fft.fftshift(Sxx, axes=0)\nf = np.fft.fftshift(f)\n\n\nplt.figure(figsize=(10, 8))\nplt.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud')\nplt.ylabel('Frequency [Hz]')\nplt.xlabel('Time [sec]')\nplt.title('Spectrogram')\nplt.colorbar(label='Power/Frequency [dB/Hz]')\nplt.show()\n</code></pre>\n<p>Output\n<a href="https://i.sstatic.net/fzanvEP6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fzanvEP6.png" alt="enter image description here" /></a></p>\n<p>You can check shape like so</p>\n<pre><code>print(f&quot;Shape of the spectrogram matrix: {Sxx.shape}&quot;)\n</code></pre>\n<p>Output:</p>\n<pre><code>Shape of the spectrogram matrix: (500, 500)\n</code></pre>\n"^^ . . . "<p>I use <code>mcc -m main.m</code> to create an exe file. When I run it on another computer that does not have <code>Matlab</code> installed, I get this error</p>\n<pre><code>Could not find version 24.1 of the MATLAB Runtime. Attempting to load mclmcrrt24_1.dll. Please install the correct version of the MATLAB Runtime. Contact your vendor if you do not have an installer for the MATLAB Runtime.\n</code></pre>\n<p>I asked GPT, and it suggested I use <code>mcc -m main.m -R -logfile</code> But it doesn't work.</p>\n<p>I want the exe file to run on a computer that did not have <code>Matlab</code> installed or MATLAB Runtime. How can I do that?</p>\n"^^ . "colors"^^ . . . . . . . . . . "matlab-compiler"^^ . . "1"^^ . "julia"^^ . . . . . "If you need implicit methods, then the extrapolation will be lacking whatever method you use, as the solution is too curvy. The stability regions for the implicit methods are larger, but also finite and shrinking for higher orders. I'm not sure if I remember this right, but the comparison in terms of function evaluations between comparable Runge-Kutta and multi-step is rather tight. And using Newton-like methods is always better than the simple fixed-point iteration."^^ . . . "Thanks but this does not correspond to the data I presented."^^ . "0"^^ . . "Some people want to think of the (radial) frequencies being in the range -π/2 to π/2 even. That depends on interpretation. But the actual algorithm uses frequencies k=0..N-1, given samples at n=0..N-1. If you explain a bit more what you really want to accomplish, we might be able to help you. Right now I’m not certain about what you need."^^ . . . . "The DFT is defined mathematically that way. So the question is why it is defined that way in maths. To me, it does feel more natural that the exponents in the imaginary exponentials increase from 0 to _N_ − 1 (see [here](https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Definition)). Also, with your proposal the cases for _N_ odd or even need to be treated differently, as in the latter case there is no center frequency. The expressions for the start and end indices in the sum that defines the DFT would be more cumbersome"^^ . . "0"^^ . . "0"^^ . . "0"^^ . "0"^^ . . . "0"^^ . . "3"^^ . "1"^^ . "0"^^ . "0"^^ . "Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking."^^ . "Hmm, after `jenv /path/to/jdk`, I see three files in `$HOME/.matlab/R2023a` which have changed, namely `matlab.mlsettings`, `history.m`, and `toolbox_cache-9.14.0-2485697813-glnxa64.xml`. Now `history.m` is just the history file and `toolbox_cache-9.14.0-2485697813-glnxa64.xml` appears to be lists of files for each toolbox. The other one `matlab.mlsettings` might contain configuration data, but it is binary data, so I can't readily edit it to put in the path I need."^^ . . . "0"^^ . "octave"^^ . "What do you mean "the results get stuck at the bus"? Can you [edit] your question so that we might be able to diagnose it without downloading and running that model ourselves?"^^ . . . . . "Hence if I do runopf and it returns infeasible, it cannot obtain an opf with the given branch limits (and equally for runpf with the given generator settings), correct?\nI am still a little confused, bc I still get violations on the branches when running opf and MATPOWER returns "feasible". Also, when running opf, one generator changes its values (always exactly one, which is weird)?\nAlso, by "running opf with tight generator limits" you mean that I should set Pmax and Pmin to similar values than my desired pg, correct? I still end up with the same gen changes. Is there something I oversaw?"^^ . "ms-word"^^ . . "Yes, thank you again for your help"^^ . . . . . . . . . . . . "How to enforce MATPOWERs runpf to keep the flow limits?"^^ . "There is nothing pertaining to the Z-transform in this post."^^ . "<p><strong>If the question is about &quot;how MATLAB maximize it's performance with the knowledge of a hybrid structured CPU&quot;, then part 1 helps with it:</strong></p>\n<p><em>Disclaimer: All credits goes to the MathWorks Support Team, I just copy and pasted it from <a href="https://www.mathworks.com/matlabcentral/answers/2062522-how-does-parallel-computing-toolbox-handle-performance-and-efficiency-core-usage" rel="nofollow noreferrer">here</a>.</em></p>\n<p>Parallel Computing Toolbox can use both types of cores. MATLAB <strong>will rely on the operating system to schedule processes across the available cores</strong>, whether they are performance-oriented or designed for efficiency. However, it's important to note that while PCT can utilize both performance (P) and efficiency (E) cores, the best practice for computational tasks is to start with a number of parallel workers equivalent to the number of physical P cores. This is because P cores are akin to traditional physical cores in terms of computational capability, while E cores are optimized for power-saving and less intensive tasks.</p>\n<p><strong>From R2024a onwards Parallel Computing Toolbox's local 'Processes' profile will use a number of default workers equal to the number of P cores on the machine.</strong>\nThis can be altered by the same steps in the link at the bottom.</p>\n<p><strong>Windows Power Plan</strong></p>\n<p>If you are using Windows, you may wish to look at adjusting your Windows Power Plan. If this is set to ‘balanced’ then Windows may deprioritise background or unselected applications so they will only run on the E cores of the system. Setting the power plan to ‘High Performance’ should cause the Intel Thread Director to be able to select which workloads are best suited to each core.</p>\n<p><strong>Performance Expectations</strong></p>\n<p>You may still see performance gains when including efficiency cores in your parallel computations, but the scaling may differ from performance cores. The actual performance improvement will depend on the nature of your code and the specific tasks being executed. In some cases, efficiency cores can handle less demanding parallel tasks effectively, allowing the performance cores to focus on more intensive computations.</p>\n<p><strong>If you wish to change the default number of cores used:</strong></p>\n<p>See also this Answer for further details on changing the number of cores leveraged by Parallel Computing Toolbox: <a href="https://www.mathworks.com/matlabcentral/answers/2042101-how-can-i-increase-the-number-of-matlab-workers-inside-parallel-computing-toolbox-to-use-all-the-cor" rel="nofollow noreferrer">https://www.mathworks.com/matlabcentral/answers/2042101-how-can-i-increase-the-number-of-matlab-workers-inside-parallel-computing-toolbox-to-use-all-the-cor</a></p>\n<p><strong>Part 2. If the question is really about &quot;How MATLAB estimate the exact number of P-cores and E-cores on a given system&quot;</strong> Then it is very hard to tell because MATLAB is a closed source software package that targets multiple OS and hardware platforms, and they constantly make changes under the hood without notifications. One speculative method might be the &quot;<a href="https://learn.microsoft.com/en-us/windows/win32/procthread/getsystemcpusetinformation" rel="nofollow noreferrer">GetSystemCpuSetInformation</a>&quot; function on Windows, which returns a <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-system_cpu_set_information" rel="nofollow noreferrer">_SYSTEM_CPU_SET_INFORMATION</a> type of structure:</p>\n<pre><code>typedef struct _SYSTEM_CPU_SET_INFORMATION {\n DWORD Size;\n CPU_SET_INFORMATION_TYPE Type;\n union {\n struct {\n DWORD Id;\n WORD Group;\n BYTE LogicalProcessorIndex;\n BYTE CoreIndex;\n BYTE LastLevelCacheIndex;\n BYTE NumaNodeIndex;\n BYTE EfficiencyClass;\n union {\n BYTE AllFlags;\n struct {\n BYTE Parked : 1;\n BYTE Allocated : 1;\n BYTE AllocatedToTargetProcess : 1;\n BYTE RealTime : 1;\n BYTE ReservedFlags : 4;\n } DUMMYSTRUCTNAME;\n } DUMMYUNIONNAME2;\n union {\n DWORD Reserved;\n BYTE SchedulingClass;\n };\n DWORD64 AllocationTag;\n } CpuSet;\n } DUMMYUNIONNAME;\n} SYSTEM_CPU_SET_INFORMATION, *PSYSTEM_CPU_SET_INFORMATION;\n</code></pre>\n<p>where the <em>EfficiencyClass</em> field could provide related information. However this is not a definitive answer and there might never be one.</p>\n"^^ . . "performing x[:signal_length] will result in having a 5ms instead of 1 sec spectrogram which is not the case with Matlab. 500x500 should represent 50Mhz band and 1 sec duration spectrogram"^^ . . . . "0"^^ . . . . "nifti"^^ . . . "0"^^ . . "0"^^ . . . "2"^^ . . "0"^^ . . . "1"^^ . "<p>I am attempting to create a MATLAB app programmatically to have it be more organized. As such I have split up code into different files based on what it does, I have one file to initialize the buttons on the screen. When I attempt to build a function callback for a button I seem to successfully build it. No errors are shown in the terminal, however I get an audible Windows Error noise and the callback action is not triggered. Here is my code:</p>\n<pre><code>function obj = selectLoad( grid ) \n %Create file load 1\n obj.fileLoad1 = uibutton(grid, 'push');\n obj.fileLoad1.FontSize = 36;\n obj.fileLoad1.Layout.Row = [8 9];\n obj.fileLoad1.Layout.Column = 1;\n obj.fileLoad1.Text = 'Load 1';\n obj.fileLoad1.ButtonPushedFcn = {@fileLoad1Callback}; \nend\nfunction fileLoad1Callback(src, event)\n fileLoad1.Text = 'Ice Cream';\nend\n</code></pre>\n<p>grid here is an argument I pass from my main initilization file that has the uigridlayout for the entire app.\nNo error code is present so it is very difficult for me diagnose the issue.</p>\n"^^ . . "0"^^ . . . "0"^^ . . . "0"^^ . . . "1"^^ . . . . . "Please attach the Excel input file, or a portion of such file. Readers should be able to reproduce the question. Without the Excel file you describe in the question, or part of it, there's no way to reproduce your question."^^ . "OK, so in the 1000x1000 case the array is indeed huge. >15 GB in memory. You cannot do that. So I'll repeat what I deleted from my earlier comment when I was confused about the size of the arrays: either don't compute the full 4D array, or if you really need to do so, then compute it and write it out in sections so that you don't need to keep the whole thing in memory at once."^^ . "Where (in what file and directory) is the path to the Java JDK stored in Matlab?"^^ . "2"^^ . . . "1"^^ . "0"^^ . "0"^^ . . . . . "<p>I am trying to create a MATLAB code that takes input and output signals from an Excel file. In the first column of the file, there is the time at which the data was acquired, in the second column are the amplitude response data. In the third column, there are the time instants of the input, and in the fourth column, the amplitudes provided as input. Since the output data is generated by another software, there are fewer output data points than input data points. My goal, as stated in the subject, is to create a MATLAB code that can generate a Bode plot to find the resonance frequency.</p>\n<p>I have tried using spline interpolation to increase the number of output points, and then I perform the FFT on both to find the gain. Additionally, I have tried using the MATLAB function pwelch, but I did not obtain acceptable results in terms of noise and peaks. I think I might be doing something wrong. Below is my code. I expect a resonance frequency between 140 and 250 Hz, and I expect there not to be all that noise.</p>\n<pre><code>clear \nclose all\nclc\n%% Excel\nfiles = dir('*.xlsx');\nt0 = 2;\nfigure;\nfor i = 1:length(files)\n x_out = [];\n x_in = [];\n t_out = [];\n t_in = [];\n raw = readtable(files(i).name);\n %% Definition of Input\n t = linspace(0, 0.36, 1024);\n freq = str2num(extractBefore(files(i).name, '.xlsx'));\n t_in = t;\n x_in = sin(freq * 2 * pi * t);\n x_in = spline(t_in, x_in, t);\n \n %% Definition of Output\n t_out = raw{:, 1} - t0; % From 0-0.36s \n x_out = raw{:, 4};\n t_out = t_out(~isnan(t_out));\n x_out = x_out(~isnan(t_out)) / 9810; %Conversion from mm to units of gravity\n \n %% Interpolation\n x_out_interp = spline(t_out, x_out, t_in);\n \n %% Pwelch\n window = hanning(256);\n noverlap = round(length(window) * 0.66); % 66% overlap\n Fs_in = 1 / (mean(diff(t_in)));\n Fs_out = 1 / (mean(diff(t_out)));\n [pxx_in, f_in] = pwelch(x_in, window, noverlap, [], Fs_in);\n [pxx_out, f_out] = pwelch(x_out_interp, window, noverlap, [], Fs_out);\n \n %% Plot PSDs\n figure(2)\n subplot(2, 1, 1)\n hold on\n plot(f_in, 10 * log10(pxx_in), DisplayName=files(i).name)\n title('Power Spectral Density of Input Signal')\n xlabel('Frequency [Hz]')\n ylabel('Power/Frequency [dB/Hz]')\n grid on\n legend(&quot;show&quot;)\n\n subplot(2, 1, 2)\n hold on\n plot(f_out, 10 * log10(pxx_out), DisplayName=files(i).name)\n title('Power Spectral Density of Interpolated Output Signal')\n xlabel('Frequency [Hz]')\n ylabel('Power/Frequency [dB/Hz]')\n grid on\n legend(&quot;show&quot;)\n \n %% Gain\n gain = 10 * log10(abs(pxx_out) ./ abs(pxx_in));\n \n %% Plot Bode\n figure(3)\n hold on\n semilogx(f_in, gain, DisplayName=files(i).name)\n title('Bode Plot - Gain')\n xlabel('Frequency [Hz]')\n ylabel('Gain [dB]')\n grid on\n xlim([0 1000])\n legend(&quot;show&quot;)\nend\n</code></pre>\n<p>Input:<br />\n<img src="https://i.sstatic.net/KPYoXxeG.png" alt="Input" /></p>\n<p>Output:<br />\n<img src="https://i.sstatic.net/AhJtU38J.png" alt="Output" /></p>\n<p>The input can also be generated in MATLAB without being extracted from an Excel file, as long as it has an amplitude of 1 and a frequency of 140 Hz. The time duration is equal to 0.36s</p>\n<p><a href="https://docs.google.com/spreadsheets/d/16Hvf9lEa59oxs-2byviH7oi6aFxnETI6/edit?usp=sharing&amp;ouid=108748695423960784184&amp;rtpof=true&amp;sd=true" rel="nofollow noreferrer">Excel file open</a></p>\n<p>In this Excel file, the results derived from the FEM analysis are contained (1st column: time [s], 2nd column: amplitude, which should be divided by 9810 to convert it into gravity units), and it is configured as the output for the Bode diagram. The sinusoidal input for plotting the Bode diagram is generated by the MATLAB code.</p>\n"^^ . "0"^^ . . "0"^^ . "Note that the FFT computes a discrete Fourier transform, not a continuous-domain Fourier transform. They are not the same thing, even though the former can be used to approximate the latter. The DFT is periodic, both in the input and the output. You need to take this into account. You also need to take sampling theory into account."^^ . "0"^^ . . . "1"^^ . "2"^^ . "1"^^ . "0"^^ . . . "Of course there will be rounding errors that will/can result in wildly different results. But the point of numerical simulations is to get as close to the truth as possible. Mathematically (so with infinite precision and time steps) I think it should be possible to shrink a system and get a perfect analogous system. One chooses the error tolerances so that the result is reasonably correct with reasonable runtime. My question is: How do relTol and absTol scale with the system. That has nothing to do with chaos and the same question could be applied to any differential equation..."^^ . "0"^^ . "How to create 3D surface with different layers that each have their own colormap in matlab?"^^ . . . . . . . . "matlab rref with symbolic matrix"^^ . . . . "<p>You can't. Not unless you have a Matlab coder license and generate C code from which you can actually compile a stand alone executable. You can redistribute the Matlab runtime with your current application: <a href="https://www.mathworks.com/products/compiler/matlab-runtime.html" rel="nofollow noreferrer">https://www.mathworks.com/products/compiler/matlab-runtime.html</a>. Check the licenses to make sure they fit your use case.</p>\n"^^ . "arbitrary-precision"^^ . . . . "0"^^ . . . "matlab-figure"^^ . . "An exact method to systematically compute the coefficients using algebraic means was presented in my answer in https://math.stackexchange.com/questions/3473300/please-correct-if-there-a-mistake-on-my-explicit-formula-of-7th-steps-adam-bashf. Check the literature for specifics, in short, you will find that the stability region for these methods shrinks very rapidly. The consequence is that the usable step-sizes may reach the boundaries of the floating-point format, the increasing number of steps giving a corresponding increase in the amplitude of the floating-point noise."^^ . "Is it possible to stop with a breakpoint at error OR warning during Matlab run with dbstop?"^^ . . "curve-fitting"^^ . "@RobertDodier I poked around a bit, the binary file is a ZIP file. I've updated the answer."^^ . "0"^^ . "0"^^ . "I added a sentence in my question, but is it true that the algorithm uses frequencies k=0...N-1? From the definition it looks like [0, 2pi/N,..., 2Pi*(N-1)/N]."^^ . "proxy"^^ . "interpolation"^^ . . . . . . . . "<p>I’m working on a MATLAB project that requires FFT and IFFT computations on large images using GPUs. Currently, the image size is</p>\n<p>32000×25600 with double precision data. Although we need to process even larger images, we’ve reduced the size due to GPU memory constraints.</p>\n<p>We’re using two NVIDIA GeForce RTX 3080 GPUs (each with 9.51 GB of available memory) to accelerate the process. Below is a simplified version of our code:</p>\n<pre><code>**parpool('Processes', 2);\nobject = ones(32000, 25600, 'gpuArray');\nobjectFT = fftshift(fft2(object));**\n</code></pre>\n<p>However, this approach runs into GPU memory issues. I attempted to split the image into smaller chunks to manage memory better and wrote a function to divide the computation across two GPUs using spmd as shown below:</p>\n<pre><code>**function result = dualGPUFFT(image, chunkSize, inverse)\n [m, n] = size(image);\n result = zeros(m, n);\n spmd\n gpuDevice(labindex);\n disp(['Worker ', num2str(labindex), ' using GPU ', num2str(gpuDevice().Index)]);\n if labindex == 1\n localData = gpuArray(image(1:floor(m / 2), :)); % Top half\n else\n localData = gpuArray(image(floor(m / 2) + 1:end, :)); % Bottom half\n end\n localResult = gpuArray.zeros(size(localData), 'like', localData);\n numChunks = ceil(size(localData, 1) / chunkSize);\n for chunkIdx = 1:numChunks\n rowStart = (chunkIdx - 1) * chunkSize + 1;\n rowEnd = min(chunkIdx * chunkSize, size(localData, 1));\n chunk = localData(rowStart:rowEnd, :);\n if inverse\n chunkResult = ifft2(ifftshift(chunk));\n else\n chunkResult = fftshift(fft2(chunk));\n end\n localResult(rowStart:rowEnd, :) = chunkResult;\n end\n resultLocal = gather(localResult);\n if labindex == 1\n result(1:floor(m / 2), :) = resultLocal;\n else\n result(floor(m / 2) + 1:end, :) = resultLocal;\n end\n end\nend**\n</code></pre>\n<p>Unfortunately, this approach also failed to handle the memory issue effectively.</p>\n<p>Here are my key questions:</p>\n<p>How can I efficiently manage GPU memory for FFT/IFFT computations on such large images?\nAre there other chunking strategies or libraries that could handle this better in MATLAB?</p>\n<p>Does performing FFT/IFFT on GPUs for large images generally offer significant speed improvements over CPUs?</p>\n<p>I’d greatly appreciate any insights, recommendations, or alternative approaches for handling such large-scale FFT/IFFT computations.</p>\n"^^ . "0"^^ . . . . "Also, I'm not sure whether the beautiful symmetry between direct and inverse DFT (just a change of sign in the exponent and a multiplying constant) would be maintained with your suggested definition"^^ . . "<p>Your loop just returns values from the last workbook. Open 'Param10.xlsx' and compare values with averages you displayed in the question. The error is here:</p>\n<pre><code>for i = 1:length(files)\n ...\n average_values = avg_values_per_row;\n ...\nend\n</code></pre>\n<p>On every loop run average_values gets current values. As I wrote before, you need to sum something like this (don't know the exact syntax):</p>\n<pre><code> average_values = sum(average_values,numeric_data)\n</code></pre>\n<p>and after the loop divide each element of average_values by 'length(files)'.</p>\n"^^ . "0"^^ . "How can I create an FIR from difference of two impulse responses?"^^ . "1"^^ . "Oh, right, thank you! The code seems to work now, so I guess the next step is for me to figure out how to save the "out" variable in the nifti format - instead of passing more character array around (EDIT: it worked with "niftiwrite")"^^ . . . . "0"^^ . . . . . "<p>I have 2 data sets in Matlab, each one is a 2xn array of data, where the top row contains timestamps. However, not each timestamp has a data point. Now I want to compare these datapoints, but I cannot use the index without filtering any data points that are not mutual. So to give an example:</p>\n<pre><code>A = [ 1, 2, 3, 5, 6;\n 3, 4, 5, 7, 8 ]\n\nB = [ 1, 2, 4, 5, 6;\n 9, 8, 6, 5, 4 ]\n</code></pre>\n<p>I want to use some kind of operation or set of operations to end up with</p>\n<pre><code>A = [1, 2, 5, 6;\n 3, 4, 7, 8 ]\n\nB = [ 1, 2, 5, 6;\n 9, 8, 5, 4 ]\n</code></pre>\n<p>So that the times and datapoints match the indexes.</p>\n<p>I have used ismember to identify the indexes that are not mutual, but I'm having trouble deleting the offending columns from the original set. I multiplied the ismember output with the dataset, but all it does is set the timestamps in the columns to zero.</p>\n"^^ . . . "0"^^ . "0"^^ . . . "0"^^ . "0"^^ . . . "0"^^ . "0"^^ . "0"^^ . . . . . . . "<p>I want to pass matrix as input from .net app to matlab function</p>\n<p>Matlab function:</p>\n<pre><code>function myfunc(info);\n sort(info)\nend\n\n</code></pre>\n<p>I want info input be recieved in function like this:</p>\n<pre><code>info = [...\n 0 0 0; ... \n 0 120 0; ... \n 240 120 0; ... \n 240 0 0; ... \n ];\n</code></pre>\n<p>and .net code:</p>\n<pre><code>MLApp.MLApp matlab = new MLApp.MLApp();\n\nmatlab.Execute(@&quot;cd C:\\scripts\\myfunc.m&quot;);\n\nobject result = null;\n\nint[,] input = new int[4, 3] { { 0, 0, 0 }, { 0, 120, 0 }, { 240, 120, 0 }, { 240, 0, 0 } };\n\nmatlab.Feval(&quot;myfunc&quot;, 0, out result, input);\n\n</code></pre>\n<p>This gives me error in Feval line--&gt; &quot;error using norm first argument must be single or double.&quot;</p>\n<p>And when I change input to be like this</p>\n<pre><code>int[,,] input = new int[4, 1, 3] {\n { {0, 0, 0} },\n { {0, 120, 0} },\n { {240, 120, 0} },\n { {240, 0, 0} }\n};\n</code></pre>\n<p>It gives another error --&gt; 'index in position 1 exceeds array bounds. index must not exceed 1</p>\n<p>How to solve this?</p>\n"^^ . . . . "0"^^ . "0"^^ . . . "1"^^ . . "3"^^ . "<p>I'm encountering some very weird behaviour in some MATLAB code I've written, and can't quite tell why. If I increment the loop from 0.01 in steps of 0.01 to 0.09, all values are correct. However, if I step from 0.01:0.10, a single extra step, MOST values are correct but some previous ones get absolutely messed up. The weird thing is that the loop doesn't depend on any previous values, each iteration is 'fresh' so I'm kind of perplexed why this is happening. Any idea? I should also note that if I run the problem values independently out of the loop, the correct answer is obtained. MWE under images...</p>\n<p><a href="https://i.sstatic.net/ARJHcn8J.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ARJHcn8J.png" alt="enter image description here" /></a></p>\n<p>MWE:</p>\n<pre><code> v = [0.5];\n pv = 0.01:0.01:0.1; %broken version..\n n = 1000;\n h = 3.841;\n fp = zeros(size(pv)); % Preallocate to avoid size issues\n\n for kx = 1:length(pv)\n p = pv(kx); \n\n% Recalculate functions dependent on 'p'\na = @(y) y;\nb = @(x) x;\nc = @(x, y) p*n - y;\nd = @(x) n*(1 - p) - x;\n\nnew = @(x, y) (n.*(a(y).*d(x) - b(x).*c(x, y)).^2) ./ ...\n ((a(y) + b(x)) .* (c(x, y) + d(x)) .* (a(y) + c(x, y)) .* (b(x) + d(x))) - h;\n\nfor j = 1:length(v) \n yp = 0:p*n;\n xp = v(j).*n - yp; \n f = new(xp,yp);\n fin = find(f&lt;0);\n yv{j} = yp(fin); \n\n end\n\n % Use ndgrid dynamically for all cell elements\n grid_cells = cell(1, numel(yv));\n [grid_cells{:}] = ndgrid(yv{:});\n\n % Convert grid into combinations matrix\n combinations = cell2mat(cellfun(@(x) x(:), grid_cells, 'UniformOutput', false));\n\n % Check that each element in the row is less than or equal to the next\n valid_rows = all(diff(combinations, 1, 2) &gt;= 0, 2);\n\n % Keep only valid combinations\n filtered_combinations = combinations(valid_rows, :);\n\n i = 1;\n probs = zeros(size(filtered_combinations)); \n probs(:,1) = hygepdf(filtered_combinations(:,1),n,round(n.*p),round(v(1).*n));\n\n while i &lt; (length(v))\n\n remy = round(n.*p - filtered_combinations(:,i));\n yhits = filtered_combinations(:,i+1) - filtered_combinations(:,i);\n npick = round(n.*(v(i+1) - v(i)));\n nrem = round(n.*(1-v(i))); \n probs(:,i+1) = hygepdf(yhits,nrem,remy,npick); \n i = i +1;\n end\n\n full = prod(probs,2); \n falsepositive = 1 - sum(full)\n\n % Store results in 'fp' array\n fp(kx) = falsepositive;\n\n % Explicitly reset variables if needed (avoiding clearvars)\n end\n</code></pre>\n"^^ . "1"^^ . . . . . "What are the values of `[rows,cols,slices]` after that first line?"^^ . . "Just out of curiosity, which test framework allows for this? I don’t know many, but the few I do know do not allow for inter-dependent test cases. I guess you could fudge something with global variables, but how are you going to force the four tests being run in the right order? I honestly think that your four steps are part of a single test."^^ . . "0"^^ . . . . "0"^^ . . "0"^^ . . . "0"^^ . "How to properly include the DC component in a MATLAB log-log plot for spectral analysis?"^^ . . "qr-code"^^ . "butterworth"^^ . . . "0"^^ . . "3"^^ . . . "0"^^ . . . . "0"^^ . . . "Confused with matlab arbitrary precision toolboxes"^^ . . "The FFT is an algorithm that computes a DFT, not a continuous-domain FT. The periodicity is N, the length of the signal. In a discrete world it makes no sense to have a periodicity of 2π, since that is not an integer number."^^ . . . "0"^^ . . . "<p>The Code</p>\n<pre><code>Rm = corr(timeModel, 'Type', 'Spearman');\n\nRm\n%First row of Rm contains the correlation coefficients between the values of avgExcTime and the expected execution times for all the possible values of KEY3:0\nRc = Rm(1,2:17);\n%The entry of Rc with the highest positive value corresponds to the guessed\n%key (the first entry of Rc is 1 and corresponds to the autocorrelation of\n%avgExcTime, therefore is discarded)\n[corr,idx] = max(Rc);\nguessedKeyNibble = idx-1```\n\nThe error\n</code></pre>\n<p>Index in position 1 is invalid. Array indices must be positive integers or logical values.</p>\n<p>Error in Part3 (line 60)\nRm = corr(timeModel, 'Type', 'Spearman');\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^```</p>\n<p><strong>What can fix this? The TimeModel has a size of 16 x 17 which is correct and I am really lost as to what is going wrong here?</strong></p>\n"^^ . . . . . . . . "3"^^ . . . "0"^^ . "If someone had a real-world problem that depended on E-core detection, support might answer with details. Otherwise some reverse-engineering might shed some light, for example `strace` on Linux or an equivalent tool on Windows can trace what system-calls a process makes. But that would only tell us if a Windows version of MATLAB calls `GetSystemCpuSetInformation` at all, not whether it checks the `EfficiencyClass` field in the output. Interesting that such a field exists at all; the docs mention ARM bit.LITTLE which predates Alder Lake's implementation of the same idea by several years."^^ . . . . "0"^^ . "0"^^ . "0"^^ . "1"^^ . "I have found one error. Mistakenly, I forget to set the parameterVector with the new weight just before the second call of the jacobian function. But the model still can't converge. I checked input and output values with ready made function in MatLab. It works with no problem. There is still convergence problem but this time error function not increasing but stuck around 1."^^ . "Why can't you save the state, do the method that takes 1ms and if it doesn't get the right answer then and only then use the slower method. Otherwise you have to add something in the iterative code loop to give up after N seconds of wall clock time. IOW "this line of code" needs to have a way of returning a timeout error to your program."^^ . . . . . . . "parameter-tuning"^^ . "0"^^ . . . . . . . . "<p>I have the following system of differential equations that arose form circuit analysis where the following simplification was made.</p>\n<p><a href="https://i.sstatic.net/CnaSpFrk.png" rel="nofollow noreferrer">Simplification of equations</a></p>\n<p>The systems of equations is as follows:</p>\n<p><a href="https://i.sstatic.net/AhN9XV8J.png" rel="nofollow noreferrer">System of Equations</a></p>\n<p>I created 2 MATLAB files, the first where I define each I_x as a symbolic variable and a second file where I define each I_x as a function of time I_x(t). When I try to find I_4 as a function of time in file 2. I get an error</p>\n<pre><code>error: structure has no member 'I4'\nerror: called from\n Gauging_Circuit at line 12 column 1\n</code></pre>\n<p>Below are the tests I preformed:</p>\n<pre><code>% File 1\nsyms I1 I2 I3 I4 R1 R2 R3 C1 C2 C3 Vi;\neqn1 = Vi == I1*((1/C1) + R1) + I2*(-(1/C1)) + I3*(0) + I4*(0);\neqn2 = Vi == I1*(-(1/C1)) + I2*((1/C1)+(1/C2)+(1/C3)) + I3*(0) + I4*(0);\neqn3 = Vi == I1*(0) + I2*(-(1/C3)) + I3*((1/C3) + R3) + I4*(0);\neqn4 = Vi == I1*(0) + I2*(-(1/C2)) + I3*(0) + I4*((1/C2)+R2);\n\n% Try lin solve, If it doesnt work, Try solve function below\n%[A, B, C, D] = equationsToMatrix([eqn1, eqn2, eqn3, eqn4], [I1, I2, I3, I4]);\n%X = linsolve(A,B);\n\nsol = solve([eqn1, eqn2, eqn3, eqn4], [I1, I2, I3, I4]);\ndisp(sol.I4)\n</code></pre>\n<p>File 1 output:\n<a href="https://i.sstatic.net/8MBuuD9T.png" rel="nofollow noreferrer">Output From file 1 Screenshot</a></p>\n<p>When I try to make each current a function of time I_x(t) I get an error. Below is the code and output from file 2.</p>\n<pre><code>% File 2\nsyms I1(t) I2(t) I3(t) I4(t) R1 R2 R3 C1 C2 C3 Vi(t);\neqn1 = Vi == I1(t)*((1/C1) + R1) + I2(t)*(-(1/C1)) + I3(t)*(0) + I4(t)*(0);\neqn2 = Vi == I1(t)*(-(1/C1)) + I2(t)*((1/C1)+(1/C2)+(1/C3)) + I3(t)*(0) + I4(t)*(0);\neqn3 = Vi == I1(t)*(0) + I2(t)*(-(1/C3)) + I3(t)*((1/C3) + R3) + I4(t)*(0);\neqn4 = Vi == I1(t)*(0) + I2(t)*(-(1/C2)) + I3(t)*(0) + I4(t)*((1/C2)+R2);\n\n% Try lin solve, If it doesnt work, Try solve function below\n%[A, B, C, D] = equationsToMatrix([eqn1, eqn2, eqn3, eqn4], [I1, I2, I3, I4]);\n%X = linsolve(A,B);\n\nsol = solve([eqn1, eqn2, eqn3, eqn4], [I1(t), I2(t), I3(t), I4(t)]);\ndisp(sol.I4)\n</code></pre>\n<p>File 2 Output (Actual name is &quot;Gauging_Circuit&quot;):</p>\n<pre><code>error: structure has no member 'I4'\nerror: called from\n Gauging_Circuit at line 12 column 1\n</code></pre>\n<p>Why am I getting this error? When I change both files so that line 12 <code>disp(sol.I4)</code> becomes <code>disp(sol)</code>, I get the exact same outputs but addressing I4 gives me an error in the second file.</p>\n"^^ . "1"^^ . "0"^^ . . "3"^^ . . . "My data is Matlab Datetime datatype NOT a 1x1 java.lang.String."^^ . . . . . "1"^^ . "2"^^ . . "0"^^ . "I don't think you can do that. I think you need to rewrite the first bit of code to be aware of how long it's running, and have it return an error value (or error out) if it's taking too long. I assume that bit of code has a loop, in the loop you can check how long it's been running and just `error` if it's too long. The calling code can `try`/`catch` and run the second bit of code in the `catch` part."^^ . . . . . "1"^^ . . . . . . "1"^^ . . "Thank you Cris and Wolfie. Now it's working:\nsample=[-1,-1,-1,1.5,2,2.5];\nz=0;\n for i=1:100\n outcome(i)=randsample(sample,1)*(2^z);\n if outcome(i)>0\n z=0;\n else\n z=z+1;\n end;\n end;"^^ . "latitude-longitude"^^ . "0"^^ . . "1"^^ . . . . . . . . "2"^^ . . . . . . . . . . . "MATLAB - Coloring the area bounded by two curves in polar coordinate system"^^ . . . . "But when I look at the documentation of fft (https://se.mathworks.com/help/matlab/ref/fft.html), it looks like we use frequencies in the range [0, 2pi/N,..., 2Pi*(N-1)/N]. My question is, can one use the frequencies [0, L/N,..., L*(N-1)/N]?"^^ . . "0"^^ . "0"^^ . . . "Optimization and acceleration of large-scale calculations in the process of wave simulation"^^ . . "0"^^ . "0"^^ . . . . . "0"^^ . . . . . "this doesn't work because `theta` must be between 0 and 2*pi and when you modify the first line to achieve that, it colors the whole area inside of `r2` instead of the area between `r1` and `r2`.\n\nis there a way to use the `fill` function to accomplish this?"^^ . "1"^^ . "Why are you using a cell anyway? They're best suited for non-numeric or non-uniform data... You probably want to define a numeric array `sample=[-1,1.5,2,2.5];` with square brackets"^^ . . . . . "0"^^ . "2"^^ . . . . "Filtering data by matching values in Matlab"^^ . . . . "<p>You want a 2D output array, don’t compute the full 4D array and then project it. Instead, compute the projection in your loop.</p>\n<p>The intermediate 4D array in the case of a 1000x1000 output is more than 15 GB, which means your 16 GB system cannot hold it in memory in its entirety (since MATLAB and the OS also need some space), and will swap out portions to disk.</p>\n<p>If the loop were to index the array as <code>eta(:,:,i,j)</code> then it wouldn’t be so bad, as you’re writing to a contiguous part of memory. But since you index <code>eta(i,j,:,:)</code>, every loop iteration is writing to bytes all across the 15 GB memory block. Thus, every loop iteration has your system read from disk and write back to disk most the array. This obviously slows down things a lot, and is called “thrashing”, because in the days of spinning hard disks, this made a lot of noise.</p>\n<p>In general, when writing loops, you should always consider the order that array elements have in memory, and loop such that you access array elements in memory order as much as possible. This optimizes the usage of the system’s cache. In MATLAB, arrays are stored with the elements along the 1st dimension contiguous in memory. So you don’t want the first dimension index being the outer loop, and you don’t want to access elements along the last dimension(s) as a single block.</p>\n<p>To project inside the loop, instead of</p>\n<pre class="lang-matlab prettyprint-override"><code>eta = zeros(length(x),length(y),length(theta),length(w));\nfor i = 1:length(x)\n for j = 1:length(y)\n eta(i,j,:,:) = eta0 .* cos(w * t - Kx .* i - Ky .* j + phase);\n end\nend\netaW = sum(eta,4);\netaWA = sum(etaW,3);\n</code></pre>\n<p>write</p>\n<pre class="lang-matlab prettyprint-override"><code>etaWA = zeros(length(x),length(y));\nfor j = 1:length(y)\n for i = 1:length(x)\n etaWA(i,j) = sum(eta0 .* cos(w * t - Kx .* i - Ky .* j + phase), 'all');\n end\nend\n</code></pre>\n<p>Note how I not only added the <code>sum</code> over all dimensions inside the loop instead of at the end. I also swapped the loop order, so that the inner loop goes over the first dimension. This is the most efficient way to loop in MATLAB.</p>\n<p>By the way, “reserving space for calculation results” is crucial. This is called pre-allocation in MATLAB speak, and avoids the huge amount of work done when enlarging an array repeatedly.</p>\n"^^ . . "1"^^ . . . "0"^^ . . "0"^^ . . "@beaker given that OP's context is weeks in a month, there always will be. I've handled the edge-case already that the list ends too soon, the only other edge case is that the list starts mid-month which could also be handled. I've expanded my example to show how it could be done in a loop for more robustness though"^^ . . . . . "I am not clear as to what you want to accomplish. Could you include example input and output data?"^^ . "0"^^ . . . "0"^^ . . . . "0"^^ . . . . . "What makes you say the results _seem wrong_? What are your expected outputs?"^^ . . "The Fourier Transform and its inverse is linear. That means that `x-y = ifft(fft(x) - fft(y)`. So I am not sure what the idea is here."^^ . "loops"^^ . . . . . . . . "STL to binary mask conversion"^^ . . "<p>Our sample set is given as {-1,1.5,2,2.5}.</p>\n<p>b = from &quot;outcome&quot; value to outcome(index100) value.</p>\n<p>There is a problem that outcome(1) cannot be equal to a matrix value. Hence I set &quot;outcome&quot; (without (1)index) equal to the matrix value. But unfortunately, yet &gt; or &lt; operators cannot work with a matrix value, And I don't know how to work with rand function.\nIn fact, I like when a negative value is randomly chosen then the next time double of it being selected, but when a positive random value is chosen it don't get doubled.\nI give you the code:</p>\n<pre><code>sample={-1,1.5,2,2.5};\nfor i=1:100\n z=i;\n outcome=randsample(sample,1);\n if outcome&gt;0\n z=1;\n else\n z=i;\n outcome(z)=(2^z)*outcome;\n end;\n if i==1\n result=outcome;\n end;\nend;\nb = outcome:outcome(100);\nresult = sum(b,&quot;all&quot;);\nplot result;\nend\n</code></pre>\n<p>Any vision for helping me?</p>\n"^^ . "0"^^ . "0"^^ . . . . . . "0"^^ . "<p>The variables that my model needs are mostly structures: say, <code>struct1, struct2, etc.</code>. The model then accesses their <strong>fields</strong> as inputs to different <strong>masks</strong>. Whether using <code>parsim or parfor/sim</code>, I need to run an initialization scripts with different inputs to the script and this main script also calls a bunch of subroutines. A non-parallel workflow is as follows:</p>\n<ol>\n<li>Change input parameters: <code>param1, param2, etc.</code></li>\n<li>Execute the main initialization script (calling other scripts)</li>\n<li>Modified structures: <code>struct1, struct2, etc.</code> are available in the Workspace</li>\n<li>Run the model</li>\n<li>Repeat Steps 1 through 4 with another set of values for param1, param2, etc.</li>\n</ol>\n<p>I tried to use <code>set_param</code> to assign the fields of the structures to the masks inside a <code>parfor</code> first to put together a <code>simin</code> before executing <code>parsim</code>, but it seems to hate executing the main initialization script before I can even use them for <code>set_param</code>. I tried using <code>parsim</code>, but basically the same approach. Thus, it fails in a similar manner.</p>\n<p>How do I convert the non-parallel workflow listed above to a parallel computing scheme?</p>\n"^^ . . . "0"^^ . . . "Welcome to SO! Without a code snippet to help diagnose, you are just asking the community to do your work for you. Please include what you have tried, with enough code to allow others to reproduce the problem. For help with this, read https://stackoverflow.com/help/minimal-reproducible-example ."^^ . "At the bottom of the documentation page I linked, there's a section titled "See Also"... That may be helpful."^^ . . "0"^^ . . . . "0"^^ . . . . "0"^^ . . . "I just got it to work, thank you so much!"^^ . . . . . "0"^^ . "2"^^ . . "You should avoid using `table` as a variable name, since you're shadowing the [in-built function `table`](https://uk.mathworks.com/help/matlab/ref/table.html)"^^ . "You just give both commands, one after the other, to stop at either condition. Each sets a breakpoint condition. You can have many, many different breakpoint conditions set up at the same time. That is why there's a `dbclear all` command."^^ . . . . . "<p>I'm trying to draw a bodeplot of a discrete contorl system with the &quot;ss&quot; and &quot;bodeplot&quot; function:</p>\n<pre class="lang-none prettyprint-override"><code>% X(k+1) = AX(k)+Bu(k)\n% y(k) = CX(k)+Du(k)\nsys_d = ss(m_A, m_B, m_C, m_D, Ts);\nh1 = bodeplot(sys_d);\n</code></pre>\n<p>It turned out that the result is not as expected in low-frequency domain (s close to 0, z close to 1), and I further check of value of transfer fucntion at z=1 by directly calculating C*(zI-A)^{-1}<em>B=C</em>(I-A)^{-1}*B:</p>\n<pre><code>transfunc = m_C*inv(eye(size(m_A))-m_A)*m_B;\n</code></pre>\n<p>And there is a warning &quot;Matrix is close to singular or badly scaled. Results may be inaccurate.&quot;\nSo it seems that the matrix is ill-conditioned when z is close to 1, and the bodeplot function itself is not accurate. How can I solve this problem? Thanks very much!</p>\n<p>I've also tryed methods like using function &quot;evalfr&quot; to calculate the gains at many frequency points, and the results are the same.</p>\n"^^ . "Matlab fittype of a logged power law, with a y-intercept"^^ . . . "<p>It looks like you've encountered a naming conflict with MATLAB's built-in <code>corr</code> function. Here's what's happening and how you can fix it:</p>\n<h3>The Issue</h3>\n<p>You likely executed a line similar to:</p>\n<pre class="lang-matlab prettyprint-override"><code>[corr, idx] = max(Rc);\n</code></pre>\n<p>By assigning the output to a variable named <code>corr</code>, you <strong>shadow</strong> MATLAB's built-in <code>corr</code> function. As a result, any subsequent calls to <code>corr(...)</code> are interpreted as attempts to index into your variable <code>corr</code> rather than calling the function.</p>\n<h3>How to Fix It</h3>\n<ol>\n<li><p><strong>Clear the Conflicting Variable</strong></p>\n<p>Remove the <code>corr</code> variable from your workspace to restore access to the built-in function:</p>\n<pre class="lang-matlab prettyprint-override"><code>clear corr\n</code></pre>\n</li>\n<li><p><strong>Use a Different Variable Name</strong></p>\n<p>To prevent this issue from happening again, choose a variable name that doesn't conflict with MATLAB's built-in functions. For example:</p>\n<pre class="lang-matlab prettyprint-override"><code>[maxCorr, idx] = max(Rc);\n</code></pre>\n<p>Now, you can safely use the <code>corr</code> function without any conflicts:</p>\n<pre class="lang-matlab prettyprint-override"><code>R = corr(data1, data2);\n</code></pre>\n</li>\n</ol>\n<h3>Best Practices</h3>\n<ul>\n<li><p><strong>Avoid Using Names of Built-in Functions:</strong> Always check MATLAB's documentation to ensure your variable names don't clash with existing functions.</p>\n</li>\n<li><p><strong>Use Descriptive Variable Names:</strong> Instead of generic names like <code>corr</code>, use more descriptive names such as <code>maxCorrelation</code> or <code>correlationValue</code> to enhance code readability and maintainability.</p>\n</li>\n</ul>\n<h3>Summary</h3>\n<p>By clearing the conflicting variable and choosing a unique name for your variables, you can prevent overshadowing built-in functions and ensure your code runs smoothly.</p>\n<hr />\n<p><em>Hope this helps! Let me know if you have any more questions.</em></p>\n"^^ . . "2"^^ . "0"^^ . "<p>Apparently, <code>dbstop if warning</code> and <code>dbstop if error</code> are independent, and should be called separately.\nCalling <code>dbstatus</code> shows their status, and they can be toggled independently.</p>\n"^^ . "0"^^ . . . . . "I don't know what the "sinusoid" is here, but for complex numbers the functions are `abs` and `angle`, not `phase`, according to the doc."^^ . . . . . "<p>When doing a N-body simulation, one could scale it and if done right I would expect identical behavior just on different time-scales and sizes (with minor differences due to rounding errors). If I for example place particles in a cube of size 10 and (with adjusted speeds) in a cube of size 1, I should get a smaller and faster system that is otherwise identical. This requires smaller step sizes (which are automatically chosen by the solver anyway), but it should overall take the same number of steps to get the same scaled results.</p>\n<p>With <code>ODE45</code> in Matlab I get unusable small step-sizes with the smaller system, which forces me to increase the error tolerances. But I don't know how <code>relTol</code> and <code>absTol</code> relate here. In <code>ODE45</code> <code>absTol/relTol</code> give a <code>threshold</code> which is used in the calculation of the maximum error. With the bigger system the standard error-tolerances (relTol = 1e-3, absTol = 1e-6, so threshold = 1e-3) work fine. I also got good results if I change these error-tolerances by the same factor, so <code>threshold</code> stays the same.</p>\n<p>But with a scaled system, I suspect that <code>threshold</code> should also change and thus the ratio <code>absTol/relTol</code>. But I have no idea by what amount (or at all). For the small system going to <code>relTol = absTol = 1</code> seems to work, but I want to make sure that this is equivalent to the bigger system.</p>\n<p>Can someone give me some insights on how to scale the error tolerances? Would it make sense, in the context of a N-body-simulation, to just use one of these error-tolerances (and set the other one arbitrarily high)?</p>\n"^^ . . . "2"^^ . . "1"^^ . . "fft"^^ . . . "1"^^ . . "coordinates"^^ . . . . . . . . . "2"^^ . . "0"^^ . "@Kostas I'm not familiar with CLUT file formats, but from my cursory search, it's either RGBA8888 or RGB565. So you either need an alpha channel, or you need to reduce the color space. Can you update your question with the format you want to use for your example? Getting the lookup table data is simple in MATLAB for the case you've presented, `lut = squeeze(img(1,:,:))`. Now it's just a question of writing the formatted data."^^ . . "0"^^ . "0"^^ . "0"^^ . "<p>The first thing you should be doing is looking at the orange underlined warning in your editor about <code>data_class</code> growing with each loop iteration. Initialising it before all of your loops with this saves a large portion of the runtime immediately</p>\n<p><strong>Pre-allocate <code>data_class</code> before the loops</strong>:</p>\n<pre><code>szout = [sz, [numel(edge_X),numel(edge_Y)]-1];\ndata_class = NaN(szout);\n</code></pre>\n<p>But the main bottleneck is calling <code>histcounts2</code> on every value individually, you can make large time savings by bringing it outside of the <code>ii/ij</code> loops, and instead of using the first input as a count of <code>1</code> for the bin it's in, use the 4th and 5th outputs which store the bin each value should go into. In your case this is the row and column indices.</p>\n<p>Here are some timings:</p>\n<ul>\n<li>Baseline code: <strong>20.53sec</strong></li>\n<li>Pre-allocating <code>data_class</code>: <strong>7.75sec</strong> (-62% total runtime)</li>\n<li>De-nest <code>histcounts2</code>: <strong>0.53sec</strong> (-97% total runtime)</li>\n<li>Only assign non-zero values: <strong>0.10sec</strong> (-99.5% total runtime)</li>\n</ul>\n<p><strong>De-nest <code>histcounts2</code></strong></p>\n<pre><code>sz = size(data);\nszout = [sz, [numel(edge_X),numel(edge_Y)]-1];\ndata_class = NaN(szout);\nfor ix = 1:sz(1)\n for iy = 1:sz(2)\n\n g_X = data_X(ix, iy, :, :);\n g_Y = data_Y(ix, iy, :, :);\n [~,~,~,bx,by] = histcounts2(g_X, g_Y, edge_X, edge_Y);\n bx = squeeze(bx);\n by = squeeze(by);\n g_data = squeeze( data(ix, iy, :, :) );\n \n for ii = 1:sz(3)\n for ij = 1:sz(4)\n g_new = zeros(szout(end-1:end));\n g_new(bx(ii,ij),by(ii,ij)) = g_data(ii,ij);\n data_class(ix,iy,ii,ij,:,:) = g_new; \n end\n end\n end\nend\n</code></pre>\n<p>Further, you don't need to initialise the array of zeros <code>g_new</code> for every slice just to set one value. Instead, initialise <code>data_class</code> as a matrix of zeros and just override the specific values you're interested in:</p>\n<p><strong>Only assign non-zero values</strong></p>\n<pre><code>sz = size(data);\nszout = [sz, [numel(edge_X),numel(edge_Y)]-1];\ndata_class = zeros(szout);\nfor ix = 1:sz(1)\n for iy = 1:sz(2)\n\n g_X = data_X(ix, iy, :, :);\n g_Y = data_Y(ix, iy, :, :);\n [~,~,~,bx,by] = histcounts2(g_X, g_Y, edge_X, edge_Y);\n bx = squeeze(bx);\n by = squeeze(by);\n g_data = squeeze( data(ix, iy, :, :) );\n \n for ii = 1:sz(3)\n for ij = 1:sz(4)\n data_class(ix,iy,ii,ij,bx(ii,ij),by(ii,ij)) = g_data(ii,ij); \n end\n end\n end\nend\n</code></pre>\n<p>You could do something with <code>sub2ind</code> to get rid of the <code>ii/ij</code> loops entirely, but in a quick test that didn't show any performance over just using the loops.</p>\n"^^ . . . "matlab"^^ . . "<p>In Matlab, I need to perform a calculation. There are two ways I can do this calculation, but I don't know <em>a priori</em> which one will be easier. One way will take the computer a millisecond to finish, and the other will take minutes. So I need a way to ask Matlab how long it's been stuck on one line of code. Something like this:</p>\n<pre><code>start timer\nrun this line of code\nif 0.1 second has passed\n stop and run this line of code\nend\n</code></pre>\n<p>Is this possible?</p>\n<p>Note that this question <a href="https://stackoverflow.com">https://stackoverflow.com/questions/21925137/how-can-i-abort-program-execution-in-matlab</a> is not relevant because I don't want to actually stop the program.</p>\n"^^ . . "1"^^ . . . "Calculating Eigenvalues of 3D-functions with eigs"^^ . . "0"^^ . . . . "Patching a color gradient with respect to given angular data"^^ . . "0"^^ . . "rest"^^ . "Use MATLAB to execute Excel What-If Goal Seek Analysis"^^ . "<p>I am trying to make a multiplication table for an assignment but anytime I run the script, the formatting is messed up and it wouldn't repeat num1 for every new line.</p>\n<p>(What I want this code to do is that the first number is a normal scalar (ie.12) and then the minimum and maximum is a bunch of different numbers (ie. 2-20), I want it to print 12x2=24 , 12x3 = 24, ... 12x20= 240)</p>\n<p>This is the code I tried and for some reason its just always messed up.</p>\n<pre><code>num1 = input('What is your first number?:');\nminnum2 = input ('What is your minimum of the second number?:');\nmaxnum2 = input('What is your maximum of the second number?:');\nnum2 = minnum2:1:maxnum2;\nproduct = num1 * num2;\ntable = [num2;product];\nfprintf ('%f x %2.0f = %3.0f \\n',num1, table);\n</code></pre>\n<p>The first line would always be correct but after that it just all messes up.</p>\n"^^ . . "0"^^ . . . . "OK, great, that makes sense. I will try that."^^ . . . . . . "3"^^ . . . . . . "0"^^ . . . . . . . "Matlab spectrogram to matplotlib spectrum"^^ . . . "3"^^ . . "1"^^ . "0"^^ . . . . "What error does that produce? Did you try `sym('-10^(-10^308)')`?"^^ . . . "0"^^ . . "0"^^ . . . . . "Just to be clear, those are user-contributed tools, not from MATLAB. You should probably ask the authors."^^ . . "I found the answer. thanks for your effort my friend"^^ . "Doesn't seem like scaling issue. Data went up 25x. Time went up less than that. You can try adding periodic print to screen messages like `Nreport=round(length(x)/100);` ... `if not(rem(i,Nreport);` ...`disp(['Calculating eta for i = ',i,' j = ',j)`. That's something I'd typically do for any large amount of calculations or repeated procedures."^^ . "0"^^ . . . . "Matlab resampling hypothesis test correlation - Why Do the P-Value and Confidence Interval for My Correlation Test Give Different Results?"^^ . "0"^^ . . . . . . "0"^^ . "0"^^ . "plot"^^ . . "It’s a method of a class. You need to create an object of that class and then call the object’s method. In MATLAB, functions don’t need to be methods of a class. You can make regular old functions. It’s not Java."^^ . "1"^^ . . . "QR codes are located, basically, by scanning across the image and looking for a pattern of edges of relative distance 1,1,3,1,1, which is characteristic of the "finder patterns". this approach is detailed in the original paper/specification. your approach looks ad-hoc. I don't see that leading far."^^ . . "1"^^ . . . "1"^^ . "1"^^ . . "1"^^ . "Matlab standalon application with loaded .net framework"^^ . "0"^^ . "2"^^ . . "0"^^ . "Have you considered using the [`symbolic`](https://www.mathworks.com/help/symbolic/create-symbolic-numbers-variables-and-expressions.html) data type and [`vpa`](https://www.mathworks.com/help/symbolic/sym.vpa.html)? Computation will be slower, but you get arbitrary precision"^^ . "0"^^ . . . . . . "0"^^ . . . "2"^^ . . . . . "`cell{:}` is the same as `cell{1}, cell{2}, cell{3}, …`. So it creates one input argument to `cat` for every element in the cell array. Because it’s a comma-separated list, you can’t assign it to a variable, only the first element will be assigned. Like saying `a=1, 1, 1`, the variable will be 1, and the other two 1s will be lost (comma is a statement separator there)."^^ . . . . . . . . . . . "Datatype error making PostgreSQL query from matlab"^^ . . "0"^^ . . . . . "How to accurately draw a Bode diagram of a control system in MATLAB in the case of its matrix being ill-conditioned?"^^ . "matrix"^^ . . . . "Matlab code to generate the Phase and angle of the sinusoid?"^^ . . "Obtain origin of warning issued by m-functions with code generation"^^ . "1"^^ . "<p>I am attempting to declutter my MATLAB app code by separating some of the initialization into separate .m files. For this I have set up various files for each type of component (e.g. a file for buttons, graph, etc.). I am attempting to access a function in my master initialize file from the file for buttons. My code goes as follows in the buttons .m file goes as follow:</p>\n<pre><code>classdef buttons &lt; handle\n methods\n %initializes the UI\n function buttonCreate(app)\n \n %Create file load 1\n app.fileload1 = uibutton(app.gridLayout, 'push');\n app.fileload1.FontSize = 36;\n app.fileload1.Layout.Row = [8 9];\n app.fileload1.Layout.Column = 1;\n app.fileload1.Text = 'Load 1';\n\n %proceeds to create the rest of the buttons\n end\n end\nend\n</code></pre>\n<p>Now I attempt to access the <code>buttonCreate()</code> function in my master initialize file <code>initialize.m</code>:</p>\n<pre><code>classdef initialize &lt; handle\n properties \n fig\n gridLayout\n axes\n\n fileload1\n end\n methods\n %initializes the UI\n function init(app)\n %create canvas\n import buttons.*;\n fig = uifigure;\n fig.Position = [100 100 1920 1080];\n movegui(fig,'center');\n fig.Name = &quot;Audio Editor&quot;;\n\n %Create grid layout\n gridLayout = uigridlayout(fig);\n gridLayout.ColumnWidth = {'1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x'};\n gridLayout.RowHeight = {'1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x', '1x'};\n\n buttonCreate(app);\n\n end\n end\n %code for calling and deleting\n methods\n %calls code to create canvas upon app start\n function app = initialize\n init(app)\n end\n %removes the app and deletes app.fig\n function delete(app)\n delete(app.fig);\n end\n end\nend\n</code></pre>\n<pre class="lang-none prettyprint-override"><code>Error in initialize/init (line 41)\n buttonCreate(app);\n ^^^^^^^^^^^^^^^^^^\nError in initialize (line 54)\n init(app)\n ^^^^^^^^^\n</code></pre>\n<p>This resulted in the <code>UIFigure</code> still being created, but with no button and the terminal giving the error given above.</p>\n"^^ . . "get_param of Bus Selector is too slow"^^ . "1"^^ . . . . . "What is the purpose of the second file? What do you expect to gain by adding the “`(t)`” everywhere?"^^ . "simulation"^^ . "Adding a comment here a similar thread I found in MATLAB Answers. https://in.mathworks.com/matlabcentral/answers/414694-how-can-i-protect-the-intellectual-property-of-my-simulink-model"^^ . "I see two issues with this approach, 1) I assume you are printing your coefficients into the console and copying them into matlab. The issue with this is that for visualization the values maybe truncated which can lead to stability problems especially for higher order IIR filters. Rather save the coeffs in python and load them in Matlab. 2) Excluding the zeros and changing the indexes of the nominator coefficients will change the filter characteristics, compare it using matlabs `fvtool`. Minor comments, for higher order IIR filters it is recommended to use SOS structures for stability."^^ . . . "Separately, since you are not using a [minimal example](https://stackoverflow.com/help/minimal-reproducible-example), consider commenting the type and size of your variables in your question. Indeed checking what your variables are is required for understanding your question. So help others help you!"^^ . "1"^^ . . . . "How to demodulate an AM signal in MATLAB?"^^ . . "That's a neat way to access the call stack. But it is not exactly what I am looking for as it pauses the execution. Instead I am looking for a way to inform the user of specific conditions in a m-function identified by its path. I use a warning for that but I could also just print the message. I think I haven't explained this point well enough."^^ . "that outcome:outcome(100) is odd"^^ . . . . "0"^^ . "0"^^ . "modulation"^^ . . "For large step sizes, the leading error term, which behaves according to the error, competes with the higher-degree terms. For small step-sizes the numerical error competes with the accumulated floating-point error. You want the segment between these extremes. For stiff ODE or methods with small stability regions this segment might shrink to nothing, which has effects like you described."^^ . . . . . . "@PeterCordes Yes, it does answer the question. MATLAB makes no distinction. "MATLAB will rely on the operating system to schedule processes across the available cores." That is, it is the OS that decides where each process runs. MATLAB just launches the processes."^^ . "1, 49, 1 - though I am not sure why..."^^ . . . . "<pre><code>% Parameters for the Kármán–Trefftz transformation\nbeta = .491; % Offset from the origin (adjust for trailing edge)\nn = 4; % Increase for sharper features\nb = -0.3; % Adjust for different airfoil characteristics\n\n% Circle in the complex plane\ntheta = linspace(0, 2*pi, 100); % Angle for the circle\nzeta = beta + exp(1i * theta); % Circle centered at (beta, 0) with radius 1\n\n% Kármán–Trefftz transformation\nz = (n*b*(zeta + b).^n + (zeta - b).^n) ./ ((zeta + b).^n - (zeta - b).^n);\n\n% Create subplots to display both shapes\nfigure;\n\n% Plot the circle\nsubplot(1, 2, 1);\nplot(real(zeta), imag(zeta), 'b-');\naxis equal; % Keep the aspect ratio equal\nxlabel('Real Part');\nylabel('Imaginary Part');\ntitle('Circle in the Complex Plane');\ngrid on;\n% Set y-limits for both plots to be identical\nylim([-1.3 1.3]); % Adjust based on your needs\nxlim([-1 1.9]); % Adjust based on your needs\n\n% Plot the airfoil\nsubplot(1, 2, 2);\nplot(real(z), imag(z), 'r-');\naxis equal; % Keep the aspect ratio equal\nxlabel('Real Part');\nylabel('Imaginary Part');\ntitle('Airfoil Shape via Kármán–Trefftz Transformation');\ngrid on;\n\n% Set y-limits for both plots to be identical\nylim([-.5 .5]); % Adjust based on your needs\n\n</code></pre>\n<p>I know the issues is with the formula for z but i dont how to get it to stop to create the sharp edge. <a href="https://i.sstatic.net/AJRi4wP8.png" rel="nofollow noreferrer">the image is the the figure my code prints out.</a></p>\n<p>I tried to change the beta,n,&amp; b values which did help from bringing it looking like a egg to a airfoil without sharp edge. If I gove over n=4.999 its starts to cross over x axis.</p>\n"^^ . "0"^^ . . "matlab-guide"^^ . "Isn't the entire point of a N-body simulation to illustrate that simulations like this are chaotic in nature and minuscule tolerance mistakes (beyond what is humanly/computationally tractable) will create a wildly different result? i.e. are you not just asking "how to ignore chaos theory"?"^^ . "0"^^ . . . . "In my experience, GPU FFT is not faster than a good multi-threaded CPU FFT. MATLAB's FFT is super fast."^^ . "2"^^ . . "signal-processing"^^ . . "Your MATLAB version is important here. Before R2014b, there was only one `colomap` per `figure`. Starting at R2014b, each `axes` has it's own colormap (still, only one per `axes`). There is no standard MATLAB way to have more than one `colormap` on an `axes`, you will have to resort to some manual tricks. The 2 most used methods are: (1) use 2 different `axes`, each with their respective `colormap`, then surperpose them. You will have to manually link axis limits, adjust colorbar positions and Z-order of the axis to get a desired result. This works OK for 2D plots, 3D surfaces may not mix well"^^ . "0"^^ . . . "1"^^ . . "0"^^ . "1"^^ . . "<p>I'm building my Matlab code as a standalone application (exe) using the following command</p>\n<pre><code>mcc -v -N -p -m runMyCode.m\n</code></pre>\n<p>I use Matlab 2022b which <a href="https://ch.mathworks.com/help/releases/R2022b/matlab/getting-started.html" rel="nofollow noreferrer">supports .net 5+</a>.</p>\n<p>When I run runMyCode.exe then I log the output of <a href="https://www.mathworks.com/help/matlab/ref/dotnetenv.html" rel="nofollow noreferrer">dotnetenv</a>. I states that .NET Framework 4.0.30319.42000 is loaded. The problem is that for some reason .NET is &quot;loaded&quot; at the entry point so if I add <code>dotnetenv(&quot;core&quot;)</code>, it produces an error:\n<em>.NET is loaded. To change the environment, restart MATLAB then call dotnetenv.</em> If I run the exe again, .NET Framework is still loaded.</p>\n<p>What I noticed is that if I open Matlab, run dotnetenv(&quot;core&quot;) and then run mcc then .NET Core is loaded within the exe.\nIs there a way to tell mcc what .NET version to be used for building the exe or at least build it in a way that .NET is not loaded?</p>\n"^^ . . "0"^^ . "c#"^^ . . . . "Do you want lookup with interpolation or without? —— In what form do you have your data in MATLAB? Can you post some code that represents the data?"^^ . . "cell"^^ . . . . . . "1"^^ . . "0"^^ . "replace 'error += ..' with 'error=error+.. '"^^ . . . . "0"^^ . "<p>How can I create a 3D map of the glacier (bedrock + glacier surface + debris surface) with each a different colormap in Matlab? I tried several things but it does not work. Only 1 colormap is used and not a separate one for each distinct layer. How can I solve this?</p>\n<p><a href="https://i.sstatic.net/6Hnsyq3B.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6Hnsyq3B.png" alt="enter image description here" /></a></p>\n<pre><code>close all;\nclear;\nclc;\n\n% Load data\nbedrock = double(geotiffread('bedrock_oct2023.tif'));\nicethick = ncread(file_name, 'icethick');\nh_debris = ncread(file_name, 'h_debris');\n\n% Define grid for plotting\n[X, Y] = meshgrid(1:size(bedrock, 2), 1:size(bedrock, 1));\n\n% Compute initial elevations\nelevation_glacier = bedrock + icethick(:, :, 1);\nelevation_debris = bedrock + icethick(:, :, 1) + h_debris(:, :, 1);\n\n% Create figure\nfigure('Position', [100 100 1200 800]);\nax = axes;\nhold(ax, 'on');\n% Define colormaps\nbedrock_cmap = copper(256);\nglacier_cmap = winter(256);\ndebris_cmap = parula(256);\n\n% Plot initial surfaces with different colormaps manually set using CData\nbedrock_alpha = double(icethick(:, :, 1) == 0); % Transparent where glacier exists\n\n% Plot bedrock\nbedrock_surf = surf(ax, X, Y, bedrock, 'FaceColor', 'interp', 'FaceAlpha', 1, 'AlphaData', bedrock_alpha);\nset(bedrock_surf, 'CData', bedrock, 'EdgeColor', 'none'); % Assign bedrock elevation as CData for coloring\n\n% Plot glacier\nglacier_surf = surf(ax, X, Y, elevation_glacier, 'FaceColor', 'interp', 'FaceAlpha', 1);\nset(glacier_surf, 'CData', elevation_glacier, 'EdgeColor', 'none'); % Assign glacier elevation as CData for coloring\n\n% Plot debris\ndebris_surf = surf(ax, X, Y, elevation_debris, 'FaceColor', 'interp', 'FaceAlpha', 1);\nset(debris_surf, 'CData', elevation_debris, 'EdgeColor', 'none'); % Assign debris elevation as CData for coloring\n\n% Set different color limits and colormaps\n% Bedrock surface color limits\ncaxis([2000 4500]);\ncolormap(ax, bedrock_cmap);\n% Freeze the colormap for bedrock so that changes to colormap do not affect it\nfreezeColors(bedrock_surf);\n\n% Glacier surface color limits\ncaxis([2000 4500]);\ncolormap(ax, glacier_cmap);\nfreezeColors(glacier_surf);\n\n% Debris surface color limits\ncaxis([2000 4500]);\ncolormap(ax, debris_cmap);\nfreezeColors(debris_surf);\n\n% Add glacier mask\nglacier_mask = double(icethick(:, :, 1) &gt; 0); % Convert mask to double for coloring\nglacier_mask_elev = bedrock + icethick(:, :, 1);\nmask_surf = surf(ax, X, Y, glacier_mask_elev, 'FaceAlpha', 1, 'EdgeColor', 'w');\nset(mask_surf, 'FaceColor', 'white'); % Set mask color to white directly\n% Set transparency where elevation equals bedrock (no ice)\nalpha_data = (glacier_mask_elev ~= bedrock);\nset(mask_surf, 'AlphaData', alpha_data, 'FaceAlpha', 'interp');\n\n% Add colorbars\ncb1 = colorbar('Position', [0.92 0.1 0.02 0.2]);\ncolormap(cb1, bedrock_cmap);\ntitle(cb1, 'Bedrock');\ncb2 = colorbar('Position', [0.92 0.4 0.02 0.2]);\ncolormap(cb2, glacier_cmap);\ntitle(cb2, 'Glacier');\ncb3 = colorbar('Position', [0.92 0.7 0.02 0.2]);\ncolormap(cb3, debris_cmap);\ntitle(cb3, 'Debris');\n\n% Set axis properties\nxlabel('X (m)');\nylabel('Y (m)');\nzlabel('Elevation (m)');\nset(gca, 'XDir', 'reverse', 'FontSize', 14);\ntitle('3D View of Glacier, Debris, Bedrock, and Glacier Mask Surface');\nset(gcf, 'color', 'white');\n\n% Set view and lighting\nview(45, 35);\nshading interp;\ncamlight('left');\ncamlight('right');\nmaterial dull; % Adjust material properties\nlighting phong;\n</code></pre>\n<p>I have tried the code above but the plot generates only 1 colormap for all 3 layers (bedrock + glacier + debris). I want the plot to have a distinct colormap for each of the layers.</p>\n"^^ . . . . . . . . "Well, there is some API test E2E scenarios e.g. 1/ create test workspace - 2/ create test board in this workspace use workspace ID as parameter - 3/ delete test board by created ID in this workspace - 4/ delete test workspace by ID. The goal is to have one scenario as TestClass with every step as a method, so once i get test ID in step 1/ only after test workspace is created, i need to store it for test 2/ and so on. I know that is is somehow against the concept of unit testing, but ti'd like to make it by analog of other test framework where it worked"^^ . . . . "cpu-architecture"^^ . "0"^^ . . "1"^^ . . "2"^^ . "1"^^ . . . "And preallocate `fourmatrix` to save some more time"^^ . "uncertainty"^^ . . . "Test cases are supposed to be independent. They have to do exactly the same thing every time, even if you run one individually, or if you add or remove other test cases. So whatever you are planning to do with this persistent value is contrary to the concept of unit tests. Maybe if you explain your ultimate goal, we can point you in the right direction."^^ . . . . . . . . "0"^^ . "1"^^ . . . "@beaker Thank you very much for the hints. It was nice to find your link to image -> graph conversion uses same idea I had had used already at the time."^^ . . "I'm going to say this *no converter found for element oid 1700* is coming from `octave` as I don't see `uuid` as one of the [built in types](https://docs.octave.org/latest/Built_002din-Data-Types.html). The only I can think of at this time is have `public.fn_func()` take a `text` argument and then do the cast to `uuid` in the function."^^ . "0"^^ . . . . . "2"^^ . . . . "Scaling a N-body-simulation and error tolerances"^^ . "0"^^ . . "<p>In the process of using MATLAB for <strong>image digit recognition</strong>, due to task requirements, I needed to use a <strong>BP neural network</strong>. I generated 500 images of digits from 0 to 9 and set up a <strong>two-layer neural network</strong>, but the prediction results have not reached 90%. I'm a beginner in machine learning, and I would greatly appreciate any guidance.\n<a href="https://i.sstatic.net/vxGy6xo7.png" rel="nofollow noreferrer">two-layer result</a></p>\n<pre><code>\nclc; clear;\n\n% Load training data\ntrainData = imageDatastore('D:\\Matlab_Project\\CourseProject\\BP\\Datasets\\train', ...\n 'IncludeSubfolders', true, ...\n 'FileExtensions', '.jpg', ...\n 'LabelSource', 'foldernames'); % Change extension to .jpg\ntestData = imageDatastore('Datasets/test', 'LabelSource', 'foldernames', 'FileExtensions', '.png');\n\nimageSize = [32, 32];\nnumImages = numel(trainData.Files);\n\n% Define image augmentation parameters\nimageAugmenter = imageDataAugmenter('RandRotation', [-20, 20], 'RandXReflection', true);\n\n% Create augmented image data store\naugmentedTrainData = augmentedImageDatastore(imageSize, trainData, 'DataAugmentation', imageAugmenter);\n\n% Read augmented images\ntrainFeatures = zeros(numImages, prod(imageSize));\n\nfor i = 1:numImages\n img = readByIndex(augmentedTrainData, i); % Read data by index\n trainImg = cell2mat(img{1, 1}); % Get image data\n Img = double(trainImg); % Convert to grayscale and normalize to [0, 1]\n train_img = (Img - min(Img(:))) / (max(Img(:)) - min(Img(:))); % Normalize to [0, 1]\n trainFeatures(i, :) = train_img(:)'; % Flatten normalized image and store\nend\n\n% Initialize labels\ntrainLabels = zeros(numImages, 1);\nfor i = 1:numImages\n % Get file path and extract label\n name = trainData.Labels(i);\n trainLabels(i) = double(name)-1; % Convert label to number and subtract 1 to match MATLAB indexing\nend\n\n% Generate a random permutation index\nrandomIdx = randperm(numImages);\n\n% Shuffle training data and labels according to random index\nshuffledFeatures = trainFeatures(randomIdx, :);\nshuffledLabels = trainLabels(randomIdx, :);\n\n% Split training and validation sets\ntrainRatio = 0.8;\nnumTrainImages = round(numImages * trainRatio);\n\ntrainFeatures = shuffledFeatures(1:numTrainImages, :);\ntrainLabels = shuffledLabels(1:numTrainImages, :); % Assuming valFeatures is validation set features\nvalFeatures = shuffledFeatures(numTrainImages+1:end, :); % Validation set features\nvalLabels = shuffledLabels(numTrainImages+1:end, :);\n\n% Initialize the neural network\ninputLayer = size(trainFeatures, 2);\nhiddenLayer1Size = 9; % First hidden layer node count\nhiddenLayer2Size = 1; % Second hidden layer node count\nOutputLayerSize = 10; % Corresponding to 10 labels for 0~9\n\n% Initialize feedforward weights and biases\nW1 = randn(hiddenLayer1Size, inputLayer) * sqrt(2 / inputLayer); % He initialization\nb1 = zeros(hiddenLayer1Size, 1); % Hidden layer bias initialized to 0\n\nW2 = randn(hiddenLayer2Size, hiddenLayer1Size) * sqrt(2 / hiddenLayer1Size); % He initialization\nb2 = zeros(hiddenLayer2Size, 1); % Second hidden layer bias initialized to 0\n\nW3 = randn(OutputLayerSize, hiddenLayer2Size) * sqrt(2 / hiddenLayer2Size); % He initialization\nb3 = zeros(OutputLayerSize, 1); % Output layer bias initialized to 0\n\nbatchSize = 20; % Number of samples for batch learning\nvalPredictions = zeros(size(valLabels)); % Initialize validation set predictions\nnumValBatches = ceil(size(valFeatures, 1) / batchSize); % Calculate validation set batch count\ntotalValLoss = 0;\n\nfor batch = 1:numValBatches\n % Calculate indices for the current batch\n startIdx = (batch - 1) * batchSize + 1;\n endIdx = min(batch * batchSize, size(valFeatures, 1));\n \n % Get features for the current batch\n X_val_batch = valFeatures(startIdx:endIdx, :)'; % Input, dimensions [inputSize, batchSize]\n \n % Forward propagation\n Z1_val = W1 * X_val_batch + b1; % Weighted input for first hidden layer\n A1_val = activation(Z1_val, &quot;sigmoid&quot;); % Activation output for first hidden layer\n Z2_val = W2 * A1_val + b2; % Weighted input for second hidden layer\n A2_val = activation(Z2_val, &quot;sigmoid&quot;); % Activation output for second hidden layer\n Z3_val = W3 * A2_val + b3; % Weighted input for output layer\n A3_val = softmax(Z3_val); % Activation output for output layer\n \n % Calculate cross-entropy loss\n idx = sub2ind(size(A3_val), valLabels(startIdx:endIdx)' + 1, 1:size(A3_val, 2));\n batchLoss = -mean(log(A3_val(idx))); % Cross-entropy loss calculation\n \n % Accumulate batch loss into total loss\n totalValLoss = totalValLoss + batchLoss;\nend\n\n% Calculate average validation loss\naverageValLoss = totalValLoss / numValBatches;\ndisp(['Initial Validation Loss: ', num2str(averageValLoss)]);\n\n% Backpropagation\nlearningRate = 0.0001;\nepochNum = 1000;\nbestValLoss = inf;\nnumTrainImages = size(trainLabels,1);\nbatchSize = 20;\ntrainLosses = zeros(epochNum, 1); % Store training loss for each epoch\nvalLosses = zeros(epochNum, 1); % Store validation loss for each epoch\nnumBatches = ceil(numTrainImages / batchSize);\nnumBatches = size(numBatches,1);\n\nlambda = 0.019; % Regularization strength\n\n% Adam optimizer parameters\nalpha = 0.001; % Initial learning rate\nbeta1 = 0.9;\nbeta2 = 0.999;\nepsilon = 1e-8;\n\n% Initialize parameters\nmW1 = zeros(size(W1)); vW1 = zeros(size(W1));\nmb1 = zeros(size(b1)); vb1 = zeros(size(b1));\nmW2 = zeros(size(W2)); vW2 = zeros(size(W2));\nmb2 = zeros(size(b2)); vb2 = zeros(size(b2));\nmW3 = zeros(size(W3)); vW3 = zeros(size(W3));\nmb3 = zeros(size(b3)); vb3 = zeros(size(b3));\n\n% Backpropagation\n\nfor epoch = 1:epochNum\n epochLoss = 0;\n \n for batch = 1:numBatches\n % Calculate the index for the current batch\n startIdx = (batch - 1) * batchSize + 1;\n endIdx = min(batch * batchSize, numTrainImages);\n \n % Get the data for the current batch\n X_batch = trainFeatures(startIdx:endIdx, :)'; % Input\n Y_batch = trainLabels(startIdx:endIdx)'; % Labels\n \n % Forward propagation\n Z1 = W1 * X_batch + b1; % Weighted input for the first hidden layer\n A1 = activation(Z1, &quot;sigmoid&quot;); % Activation output for the first hidden layer\n Z2 = W2 * A1 + b2; % Weighted input for the second hidden layer\n A2 = activation(Z2, &quot;sigmoid&quot;); % Activation output for the second hidden layer\n Z3 = W3 * A2 + b3; % Weighted input for the output layer\n A3 = softmax(Z3); % Activation output for the output layer\n \n % Calculate error\n idx = sub2ind(size(A3), Y_batch + 1, 1:size(A3, 2));\n epsilon = 1e-10;\n error = -mean(log(A3(idx) + epsilon)); % Use average cross-entropy\n epochLoss = epochLoss + error;\n \n % Backpropagation\n delta3 = A3; % Initialize delta3 as the probabilities from A3\n delta3(sub2ind(size(A3), Y_batch + 1, 1:size(A3, 2))) = delta3(sub2ind(size(A3), Y_batch + 1, 1:size(A3, 2))) - 1;\n delta2 = (W3' * delta3) .* diff_activation(A2, &quot;sigmoid&quot;); % Error term for the second hidden layer\n delta1 = (W2' * delta2) .* diff_activation(A1, &quot;sigmoid&quot;); % Error term for the first hidden layer\n \n % Calculate gradients\n gradW3 = delta3 * A2' / size(A3, 2) + lambda * W3; % Include L2 regularization\n gradb3 = mean(delta3, 2);\n gradW2 = delta2 * A1' / size(A3, 2) + lambda * W2; % Include L2 regularization\n gradb2 = mean(delta2, 2);\n gradW1 = delta1 * X_batch' / size(A3, 2) + lambda * W1; % Include L2 regularization\n gradb1 = mean(delta1, 2);\n \n % Update first moment estimates\n mW1 = beta1 * mW1 + (1 - beta1) * gradW1;\n mb1 = beta1 * mb1 + (1 - beta1) * gradb1;\n mW2 = beta1 * mW2 + (1 - beta1) * gradW2;\n mb2 = beta1 * mb2 + (1 - beta1) * gradb2;\n mW3 = beta1 * mW3 + (1 - beta1) * gradW3;\n mb3 = beta1 * mb3 + (1 - beta1) * gradb3;\n \n % Update second moment estimates\n vW1 = beta2 * vW1 + (1 - beta2) * (gradW1 .^ 2);\n vb1 = beta2 * vb1 + (1 - beta2) * (gradb1 .^ 2);\n vW2 = beta2 * vW2 + (1 - beta2) * (gradW2 .^ 2);\n vb2 = beta2 * vb2 + (1 - beta2) * (gradb2 .^ 2);\n vW3 = beta2 * vW3 + (1 - beta2) * (gradW3 .^ 2);\n vb3 = beta2 * vb3 + (1 - beta2) * (gradb3 .^ 2);\n \n % Compute bias-corrected estimates\n mW1_hat = mW1 / (1 - beta1^epoch);\n mb1_hat = mb1 / (1 - beta1^epoch);\n mW2_hat = mW2 / (1 - beta1^epoch);\n mb2_hat = mb2 / (1 - beta1^epoch);\n mW3_hat = mW3 / (1 - beta1^epoch);\n mb3_hat = mb3 / (1 - beta1^epoch);\n vW1_hat = vW1 / (1 - beta2^epoch);\n vb1_hat = vb1 / (1 - beta2^epoch);\n vW2_hat = vW2 / (1 - beta2^epoch);\n vb2_hat = vb2 / (1 - beta2^epoch);\n vW3_hat = vW3 / (1 - beta2^epoch);\n vb3_hat = vb3 / (1 - beta2^epoch);\n \n % Update weights and biases\n W1 = W1 - alpha * mW1_hat ./ (sqrt(vW1_hat) + epsilon);\n b1 = b1 - alpha * mb1_hat ./ (sqrt(vb1_hat) + epsilon);\n W2 = W2 - alpha * mW2_hat ./ (sqrt(vW2_hat) + epsilon);\n b2 = b2 - alpha * mb2_hat ./ (sqrt(vb2_hat) + epsilon);\n W3 = W3 - alpha * mW3_hat ./ (sqrt(vW3_hat) + epsilon);\n b3 = b3 - alpha * mb3_hat ./ (sqrt(vb3_hat) + epsilon);\n end\n \n % Calculate training loss, including L2 regularization\n trainLosses(epoch) = (epochLoss / numBatches) + (lambda / 2) * (norm(W1, 'fro')^2 + norm(W2, 'fro')^2 + norm(W3, 'fro')^2);\n \n % Validation loss calculation (without Dropout)\n valPredictions = zeros(size(valLabels));\n \n % Validation loss calculation (without loops)\n Z1_val = W1 * valFeatures' + b1;\n A1_val = activation(Z1_val, &quot;sigmoid&quot;);\n Z2_val = W2 * A1_val + b2;\n A2_val = activation(Z2_val, &quot;sigmoid&quot;);\n Z3_val = W3 * A2_val + b3;\n A3_val = softmax(Z3_val);\n \n % Select the actual class probabilities for each sample as the basis for validation loss calculation\n valIdx = sub2ind(size(A3_val), valLabels' + 1, 1:size(A3_val, 2));\n valLoss = -mean(log(A3_val(valIdx) + epsilon)); % Calculate average cross-entropy loss\n valLoss = valLoss + (lambda / 2) * (norm(W1, 'fro')^2 + norm(W2, 'fro')^2 + norm(W3, 'fro')^2); % Include regularization in validation loss\n valLosses(epoch) = valLoss;\n \n % Predict classes\n [~, predictedLabels] = max(A3_val, [], 1); \n valPredictions = predictedLabels - 1; % Subtract 1 from the index to match label range 0-9\n \n disp(['Epoch: ' num2str(epoch) ', Training Error: ' num2str(epochLoss / numBatches) ', Validation Loss: ' num2str(valLoss)]);\nend\n\n\n\n% Plot training loss and validation loss curves\nfigure;\nhold on;\nplot(trainLosses(1:epoch), 'LineWidth', 1.5);\nplot(valLosses(1:epoch), 'LineWidth', 1.5);\nxlabel('Epoch');\nylabel('Loss');\ntitle('Training and Validation Loss');\nlegend('Training Loss', 'Validation Loss');\ngrid on;\nhold off;\n\n% Predictions for the test set (without Dropout)\n%%% Simple test\ntestFeatures = zeros(numel(testData.Files), prod(imageSize));\nfor i = 1:numel(testData.Files)\n img = imread(testData.Files{i}); % Use the test dataset files\n img = imresize(rgb2gray(im2double(img)), imageSize); % Normalize and resize\n img = (img - mean(img(:))) / std(img(:)); % Standardize to zero mean and unit variance\n testFeatures(i, :) = img(:)'; % Flatten the image and store it\nend\ntestPredictions = zeros(size(testFeatures, 1), OutputLayerSize);\nfor j = 1:size(testFeatures, 1)\n X_test = testFeatures(j, :)'; % Get the feature vector for a single test sample\n \n % Forward propagation (without Dropout)\n Z1_test = W1 * X_test + b1;\n A1_test = activation(Z1_test, &quot;sigmoid&quot;);\n Z2_test = W2 * A1_test + b2;\n A2_test = activation(Z2_test, &quot;sigmoid&quot;); % Activation output for the second hidden layer\n Z3_test = W3 * A2_test + b3;\n A3_test = softmax(Z3_test);\n testPredictions(j, :) = A3_test; % Store the output probabilities\nend\n\n% Get the predicted labels based on the test predictions\n[~, finalPredictions] = max(testPredictions, [], 2);\nfinalPredictions = finalPredictions - 1; % Convert to label format\n\n</code></pre>\n<pre><code>function y = activation(x, method)\n %% Options: sigmoid, tanh, relu, softmax\n if strcmp(method, &quot;sigmoid&quot;)\n y = logsig(x); % Sigmoid activation function\n elseif strcmp(method, &quot;tanh&quot;)\n y = tanh(x); % Tanh activation function\n elseif strcmp(method, &quot;relu&quot;)\n y = max(0, x); % ReLU activation function\n elseif strcmp(method, &quot;softmax&quot;)\n % expX = exp(x - max(x)); % Adjustment for numerical stability\n % y = expX / sum(expX); % Softmax activation function\n y = softmax(x);\n else\n error('Unsupported activation method. Choose from: sigmoid, tanh, relu, softmax.');\n end\nend\n\nfunction y = diff_activation(x, method)\n % Gradient of activation functions: sigmoid, tanh, relu, softmax\n if strcmp(method, &quot;sigmoid&quot;)\n y = (x) .* (1 - x); % Derivative of sigmoid\n elseif strcmp(method, &quot;tanh&quot;)\n y = 1 - (x).^2; % Derivative of tanh\n elseif strcmp(method, &quot;relu&quot;)\n y = x &gt; 0; % Derivative of ReLU: 1 for parts greater than 0, 0 otherwise\n elseif strcmp(method, &quot;softmax&quot;)\n % Derivative of softmax: diagonal part\n s = exp(x) ./ sum(exp(x));\n y = diag(s) - (s * s');\n else\n error('Unsupported activation method. Choose from: sigmoid, tanh, relu, softmax.');\n end\nend\n</code></pre>\n<p>I also tried using a <strong>single-layer neural network</strong>, but the results were unsatisfactory.\n<a href="https://i.sstatic.net/JGI3yq2C.png" rel="nofollow noreferrer">single-layer result</a></p>\n<pre><code>clc; clear;\n\n% Load training data\ntrainData = imageDatastore('D:\\Matlab_Project\\CourseProject\\BP\\Datasets\\train', ...\n 'IncludeSubfolders', true, ...\n 'FileExtensions', '.jpg', ...\n 'LabelSource', 'foldernames'); % Change the extension to .jpg\n\ntestData = imageDatastore('Datasets/test', ...\n 'IncludeSubfolders', true, ...\n 'FileExtensions', '.png', ...\n 'LabelSource', 'foldernames'); % Test data remains unchanged\n\nimageSize = [32, 32];\nnumImages = numel(trainData.Files);\n\n% Define image augmentation parameters\nimageAugmenter = imageDataAugmenter('RandRotation', [-20, 20], 'RandXReflection', true);\n\n% Create augmented image data storage\naugmentedTrainData = augmentedImageDatastore(imageSize, trainData, 'DataAugmentation', imageAugmenter);\n\n% Read augmented images\ntrainFeatures = zeros(numImages, prod(imageSize));\n\nfor i = 1:numImages\n img = readByIndex(augmentedTrainData, i); % Use readByIndex to read data by index\n trainImg = cell2mat(img{1, 1}); % Retrieve image data\n Img = double(trainImg); % Convert to grayscale and normalize to [0, 1]\n train_img = (Img - min(Img(:))) / (max(Img(:)) - min(Img(:))); % Normalize to [0, 1]\n trainFeatures(i, :) = train_img(:)'; % Flatten and store the normalized image\nend\n\n% Initialize labels\ntrainLabels = zeros(numImages, 1); \nfor i = 1:numImages\n % Retrieve file path and extract label\n name = trainData.Labels(i);\n trainLabels(i) = double(name)-1; % Convert label to a number and subtract 1 to fit MATLAB indexing\nend \n\n% Generate a random shuffle index\nrandomIdx = randperm(numImages);\n\n% Shuffle training data and labels according to the random index\nshuffledFeatures = trainFeatures(randomIdx, :);\nshuffledLabels = trainLabels(randomIdx, :);\n\n% Split training and validation sets\ntrainRatio = 0.8; \nnumTrainImages = round(numImages * trainRatio);\n\ntrainFeatures = shuffledFeatures(1:numTrainImages, :);\ntrainLabels = shuffledLabels(1:numTrainImages, :); % Assume valFeatures are validation set features\nvalFeatures = shuffledFeatures(numTrainImages+1:end, :); % Validation set features\nvalLabels = shuffledLabels(numTrainImages+1:end, :);\n\n% Initialize neural network\ninputLayer = size(trainFeatures, 2);\nhiddenLayerSize = 9;\nOutputLayerSize = 10; % Corresponds to 10 labels (0~9)\n\n% Forward feed\nW1 = randn(hiddenLayerSize, inputLayer) * sqrt(2 / inputLayer); % He initialization\nW2 = randn(OutputLayerSize, hiddenLayerSize) * sqrt(2 / hiddenLayerSize); % He initialization\nb1 = zeros(hiddenLayerSize, 1); % Initialize hidden layer bias to 0\nb2 = zeros(OutputLayerSize, 1); % Initialize output layer bias to 0\n\nbatchSize = 50; % Number of samples per batch for batch learning\nvalPredictions = zeros(size(valLabels)); % Initialize validation predictions\nnumValBatches = ceil(size(valFeatures, 1) / batchSize); % Calculate validation batches\n\ntotalValLoss = 0;\nfor batch = 1:numValBatches\n % Calculate current batch index\n startIdx = (batch - 1) * batchSize + 1;\n endIdx = min(batch * batchSize, size(valFeatures, 1));\n \n % Get current batch features\n X_val_batch = valFeatures(startIdx:endIdx, :)'; % Input, dimensions [inputSize, batchSize]\n \n % Forward propagation\n Z1_val = W1 * X_val_batch + b1; % Weighted input for hidden layer\n A1_val = activation(Z1_val, &quot;sigmoid&quot;); % Hidden layer activation output\n Z2_val = W2 * A1_val + b2; % Weighted input for output layer\n \n % Apply softmax activation function\n A2_val = softmax(Z2_val);\n \n % Calculate cross-entropy loss\n idx = sub2ind(size(A2_val), valLabels(startIdx:endIdx)' + 1, 1:size(A2_val, 2));\n batchLoss = -mean(log(A2_val(idx))); % Cross-entropy loss calculation\n \n % Accumulate batch loss to total loss\n totalValLoss = totalValLoss + batchLoss; \nend\n\n% Calculate average validation loss\naverageValLoss = totalValLoss / numValBatches;\ndisp(['Initial Validation Loss: ', num2str(averageValLoss)]);\n\n% Backpropagation\nlearningRate = 0.01;\nepochNum = 1000;\nbestValLoss = inf;\nnumTrainImages = size(trainLabels, 1);\nbatchSize = 40;\ntrainLosses = zeros(epochNum, 1); % Store training loss for each epoch\nvalLosses = zeros(epochNum, 1); % Store validation loss for each epoch\nnumBatches = ceil(numTrainImages / batchSize);\n\nlambda = 0.005; % Regularization strength\n\n% Adam optimizer parameters\nalpha = 0.001; % Initial learning rate\nbeta1 = 0.9;\nbeta2 = 0.999;\nepsilon = 1e-8;\n\n% Initialize parameters\nmW1 = zeros(size(W1)); vW1 = zeros(size(W1));\nmb1 = zeros(size(b1)); vb1 = zeros(size(b1));\nmW2 = zeros(size(W2)); vW2 = zeros(size(W2));\nmb2 = zeros(size(b2)); vb2 = zeros(size(b2));\n\nfor epoch = 1:epochNum\n epochLoss = 0;\n \n for batch = 1:numBatches\n % Calculate current batch index\n startIdx = (batch - 1) * batchSize + 1;\n endIdx = min(batch * batchSize, numTrainImages);\n \n % Get current batch data\n X_batch = trainFeatures(startIdx:endIdx, :)'; % Input\n Y_batch = trainLabels(startIdx:endIdx)'; % Label\n \n % Forward propagation\n Z1 = W1 * X_batch + b1; % Weighted input for hidden layer\n A1 = activation(Z1, &quot;sigmoid&quot;); % Hidden layer activation output\n Z2 = W2 * A1 + b2; % Weighted input for output layer\n A2 = softmax(Z2); % Output layer activation output\n \n % Compute error\n idx = sub2ind(size(A2), Y_batch + 1, 1:size(A2, 2));\n error = -mean(log(A2(idx) + epsilon)); % Use mean cross-entropy\n epochLoss = epochLoss + error;\n \n % Backpropagation\n delta2 = A2; % Initialize delta2 as probabilities in A2\n delta2(sub2ind(size(A2), Y_batch + 1, 1:size(A2, 2))) = delta2(sub2ind(size(A2), Y_batch + 1, 1:size(A2, 2))) - 1;\n delta1 = (W2' * delta2) .* diff_activation(A1, &quot;sigmoid&quot;); % Hidden layer error term\n \n % Calculate gradients\n gradW2 = delta2 * A1' / size(A2, 2) + lambda * W2; % Include L2 regularization\n gradb2 = mean(delta2, 2);\n gradW1 = delta1 * X_batch' / size(A2, 2) + lambda * W1; % Include L2 regularization\n gradb1 = mean(delta1, 2);\n \n % Update first moment estimates\n mW1 = beta1 * mW1 + (1 - beta1) * gradW1;\n mb1 = beta1 * mb1 + (1 - beta1) * gradb1;\n mW2 = beta1 * mW2 + (1 - beta1) * gradW2;\n mb2 = beta1 * mb2 + (1 - beta1) * gradb2;\n \n % Update second moment estimates\n vW1 = beta2 * vW1 + (1 - beta2) * (gradW1 .^ 2);\n vb1 = beta2 * vb1 + (1 - beta2) * (gradb1 .^ 2);\n vW2 = beta2 * vW2 + (1 - beta2) * (gradW2 .^ 2);\n vb2 = beta2 * vb2 + (1 - beta2) * (gradb2 .^ 2);\n \n % Calculate bias-corrected estimates\n mW1_hat = mW1 / (1 - beta1^epoch);\n mb1_hat = mb1 / (1 - beta1^epoch);\n mW2_hat = mW2 / (1 - beta1^epoch);\n mb2_hat = mb2 / (1 - beta1^epoch);\n vW1_hat = vW1 / (1 - beta2^epoch);\n vb1_hat = vb1 / (1 - beta2^epoch);\n vW2_hat = vW2 / (1 - beta2^epoch);\n vb2_hat = vb2 / (1 - beta2^epoch);\n \n % Update weights and biases\n W1 = W1 - alpha * mW1_hat ./ (sqrt(vW1_hat) + epsilon);\n b1 = b1 - alpha * mb1_hat ./ (sqrt(vb1_hat) + epsilon);\n W2 = W2 - alpha * mW2_hat ./ (sqrt(vW2_hat) + epsilon);\n b2 = b2 - alpha * mb2_hat ./ (sqrt(vb2_hat) + epsilon);\n end\n \n % Store training loss for current epoch\n trainLosses(epoch) = epochLoss / numTrainImages;\n \n % Validate on validation set\n valPredictions = zeros(size(valLabels));\n numValBatches = ceil(size(valFeatures, 1) / batchSize);\n % Reset total validation loss for current epoch\n totalValLoss = 0;\n\n for batch = 1:numValBatches\n % Calculate current batch index\n startIdx = (batch - 1) * batchSize + 1;\n endIdx = min(batch * batchSize, size(valFeatures, 1));\n\n % Get current batch features\n X_val_batch = valFeatures(startIdx:endIdx, :)';\n\n % Forward propagation on validation set\n Z1_val = W1 * X_val_batch + b1; % Weighted input for hidden layer\n A1_val = activation(Z1_val, &quot;sigmoid&quot;); % Hidden layer activation output\n Z2_val = W2 * A1_val + b2; % Weighted input for output layer\n\n % Apply softmax activation for output layer\n A2_val = softmax(Z2_val);\n\n % Calculate cross-entropy loss for the batch\n idx = sub2ind(size(A2_val), valLabels(startIdx:endIdx)' + 1, 1:size(A2_val, 2));\n batchLoss = -mean(log(A2_val(idx) + epsilon));\n \n % Accumulate batch loss into total validation loss\n totalValLoss = totalValLoss + batchLoss;\n end\n\n % Calculate average validation loss for the epoch\n averageValLoss = totalValLoss / numValBatches;\n valLosses(epoch) = averageValLoss;\n\n % Display loss information\n disp(['Epoch ', num2str(epoch), ' - Training Loss: ', num2str(trainLosses(epoch)), ...\n ' - Validation Loss: ', num2str(averageValLoss)]);\n\n % Early stopping: save model if validation loss improves\n if averageValLoss &lt; bestValLoss\n bestValLoss = averageValLoss;\n bestW1 = W1;\n bestb1 = b1;\n bestW2 = W2;\n bestb2 = b2;\n patienceCounter = 0; % Reset patience counter if validation improves\n else\n patienceCounter = patienceCounter + 1;\n if patienceCounter &gt;= patience\n disp('Early stopping triggered.');\n break;\n end\n end\nend\n\n% Plot training and validation loss over epochs\nfigure;\nplot(1:epoch, trainLosses(1:epoch), '-o', 'DisplayName', 'Training Loss');\nhold on;\nplot(1:epoch, valLosses(1:epoch), '-x', 'DisplayName', 'Validation Loss');\nxlabel('Epoch');\nylabel('Loss');\nlegend;\ntitle('Training and Validation Loss');\ngrid on;\n\n% Load best model weights\nW1 = bestW1;\nb1 = bestb1;\nW2 = bestW2;\nb2 = bestb2;\n\ndisp('Training completed. Best validation loss: ');\ndisp(bestValLoss);\n\n\n</code></pre>\n"^^ . . "That isn't the descriptive bit of the error message, what's the full error message with the cause description?"^^ . . . . "0"^^ . . . "I can't advise on the Matlab but I would hazard a guess that the chess matrix is to shift the phase centre after the convolution. Otherwise the output of the convolution will be centred on the natural phase centre of the FFT at (0,0). I suspect that your problem with accuracy is because `1/sqrt(eta^2+nu^2)` only decreases slowly so that truncation errors are significant when you have a very finite grid. Try it with `exp(-x^2)` or without the `sqrt()` and I would expect much better agreement with theory."^^ . . "I think it would be good if you re-read your question with fresh eyes, and imagine what someone without your baggage could understand of this. I *think* your are talking about images here, but you don’t use that word anywhere. I *think* you have a labeled image and want to display it in some specific way. Note especially that “matrix” is a mathematical term, with a very specific meaning, and doesn’t normally contain “data”."^^ . . . . . . . . . . . "vectorization"^^ . "According to Simulink documentation the workflow for model/subsystem for IP protection we can follow https://in.mathworks.com/help/rtw/ug/generated-s-function-block-deployment.html."^^ . . . . "0"^^ . "I suspect it depends on the OS to some extent. Before Win11 the E&P core support wasn't really there. I'd hazard a guess that it uses E-core(s) for the user interface and anything that is remotely CPU bound goes to a P-core. I also expect that due to hyper threading MATLAB maxNumCompThreads default may be more than physical cores and less than twice that number. I find using around 1.6x physical cores about optimal for my problems - using more than that saturates memory bandwidth and just generates extra heat without any increase in performance."^^ . . . "<p>I'm using the Matlab Optimisation toolbox to create and solve an optimisation problem which I have called chargeprob.</p>\n<p>After running my code successfully, I want to implement a maximum calculation time.</p>\n<pre><code>options = optimoptions(&quot;linprog&quot;,&quot;MaxTime&quot;,5)\n[sol,fval,exitflag,output] = solve(chargeprob,'Options',options)\n</code></pre>\n<p>If my understanding is correct this should mean that if the solve takes longer than 5 seconds, the solver should exit saying no solution was found in time. Instead what happens is that it appears to have no effect with the solver taking in this case 30 seconds. What is the correct way to set a timeout on my solver?</p>\n"^^ . . . "This is actually a limitation of MATPOWER. The standard power flow (`runpf`) can handle fixed generation but doesn't enforce branch limits, while OPF (`runopf`) enforces branch limits but allows generation to vary.\nYou could try to approximate using `runopf` with very tight generator limits, this usually worked in my cases when I had to do analysis. Tho, you may have convergence issues due to the very tight constraints and it might still allow tiny variations in generator output, depending on the values you use."^^ . . . "Defining length for fft in Matlab"^^ . "0"^^ . . . . "levenberg-marquardt"^^ . . . . . . . . . "0"^^ . . . "0"^^ . "correlation"^^ . . . "1"^^ . "If you delete the peak and fit a polynomial to the baseline then you might stand a chance of having a problem that it can solve, but there is no way it can hope to fit a sharp peak like that. Try fitting a baseline polynomial curve to 100-750 and 1250-4500 then use that baseline to isolate your peak (and use the lowest order you can get a decent fit with). It also helps to have a decent model of a theoretical ideal peak for a peak fitting code to use."^^ . . . . "<p>You might have to use <code>pol2cart</code> to convert from polar to cartesian coordinates, which opens up more of the standard plotting functions like <code>patch</code></p>\n<p>Example input:</p>\n<pre><code>theta = linspace(0,pi,2000);\nr1 = 3 * sin(theta);\nr2 = 1 + sin(theta);\n</code></pre>\n<p>Plotting code:</p>\n<pre><code>[x1,y1] = pol2cart( theta, r1 );\n[x2,y2] = pol2cart( theta, r2 );\nfigure; hold on;\npatch([x1 fliplr(x2)], [y1 fliplr(y2)], [0.7,0.9,0.9], 'displayname', 'fill', 'linestyle', 'none')\nplot( x1, y1, 'r', 'linewidth', 2, 'displayname', 'r1' );\nplot( x2, y2, 'b', 'linewidth', 2, 'displayname', 'r2' );\nlegend( 'show' );\n</code></pre>\n<p>Note if you go past <code>pi</code> for <code>theta</code> then the definition of which region is between the lines gets a little ambiguous, but from here you have all the coordinates to define the fill boundary and the ability to calculate them differently.</p>\n<p><a href="https://i.sstatic.net/kxWGEb8R.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kxWGEb8R.png" alt="plot" /></a></p>\n"^^ . "1"^^ . . . . . . . "0"^^ . "<p>I have a MRI image of a brain, made of 25 slices, in NIFTI format (so one file containing the 3D data). I need it to have 30 slices to use a specific medical tool - how can I use interpolation to add intermediate slices (or even just slices at the end) ?</p>\n<p>I have seen the Matlab function &quot;interp3&quot; mentionned and I tried with the following code:</p>\n<pre><code>[rows,cols,slices] = size('subject.nii')\n[x1,y1,z1] = meshgrid(1:cols, 1:rows, 1:slices)\n[x2,y2,z2] = meshgrid(1:cols, 1:rows, 0.5:0.5:slices)\nout = interp3(x1, y1, z1, 'subject.nii', x2, y2, z2, 'linear', 0)\n</code></pre>\n<p>However, it returns the following error:</p>\n<blockquote>\n<p>Error using griddedInterpolant\nSample values must be of type double or single.</p>\n<p>Error in interp3 (line 132)\nF = griddedInterpolant({X, Y, Z}, V, method,extrap);</p>\n</blockquote>\n<p>How can I fix this?\nOr should I use a different function? I have also seen &quot;imresize&quot; in this forum but I can't figure out how to use it...</p>\n"^^ . . . "This assumes that there actually **is** a 3rd instance for each timestamp, which may or may not be true. Honestly, I'd rather iterate through the list."^^ . . . "MATLAB: Corr Function not working for Spearman"^^ . "0"^^ . . "Calling this merely visualization is an understatement IMO. In general, usually what you are interested when inspecting a signal's Fourier transform, is interesting peaks in it's spectrum, and there it would also be natural if it would have been ordered from `-1/dx` to `1/dx`.. The purpose of my question is to get examples of cases where it is natural to view or perform calculations upon the output of `fft` when it is ordered in it's current, natural order."^^ . "0"^^ . "How to fill a subfield based on conditions in Matlab"^^ . . "set"^^ . . "1"^^ . . . "<p>I'm translating a code from MATLAB to Julia and noticed differences in the results of the Cholesky decomposition, despite using the same input matrix.</p>\n<p>In Julia, I used:</p>\n<pre class="lang-julia prettyprint-override"><code>R = sparse(cholesky(K[perm, perm]).L)'\n</code></pre>\n<p>In MATLAB, I used:</p>\n<pre class="lang-matlab prettyprint-override"><code>R = sparse(chol(K(perm, perm)));\n</code></pre>\n<p>However, <code>nnz(R)</code> in Julia is 1404, while in MATLAB, <code>nnz(R)</code> is 1352. Exporting <code>R</code> from Julia to MATLAB gives <code>nnz(Rjulia) = 1356</code>.</p>\n<p>Could this be due to numerical precision differences? How can I ensure consistent results between both environments?</p>\n<p><code>K[perm, perm]=</code> <a href="https://justpaste.it/gxful" rel="nofollow noreferrer">https://justpaste.it/gxful</a></p>\n"^^ . "Printing out coordinates of clicked points while user draws polyline in Matlab App Designer"^^ . "There are an estimated 10^80 atoms in the universe (plus minus 10 or 20 orders of magnitude), so yes, 10^(2^32) is a ridiculously large number."^^ . "0"^^ . . . . . "What is the problem and show the code and how you did it"^^ . . "2"^^ . "1"^^ . . . . . "0"^^ . "<p>I'm working on plotting the Power Spectral Density (PSD) in MATLAB using loglog but I'm encountering an issue with the DC component (frequency = 0). Since <code>log_10(0)= -inf</code> MATLAB automatically excludes the DC component from the plot.</p>\n<p>I tried assigning a small positive value to the DC frequency, and it works to include the component in the plot. However, this approach alters the true frequency values, which I want to avoid because it doesn't align with the actual spectrum. I also considered the &quot;log-of-x-plus-one&quot; transformation but it changes the real frequency axis and doesn’t reflect the true nature of the spectral data.\nMy questions are:</p>\n<ol>\n<li><p>What are best practices for including the DC component in log-log spectral plots in MATLAB?</p>\n</li>\n<li><p>Is there a way to represent the DC component (f=0) visually without assigning an arbitrary value that distorts the frequency axis?</p>\n</li>\n<li><p>If the DC component is typically excluded, what’s the standard way to present or annotate it in such plots?</p>\n</li>\n</ol>\n<p>Any advice or insight on this would be greatly appreciated!</p>\n<pre><code>[PSD_u_mean, f_u_mean] = pwelch(detrend(nanmean(u,2)), hanning(WL), floor(WL/2), WL, FS); \n \n%%\nfigure;\nloglog(f_u_mean, PSD_u_mean, 'LineWidth', 1.5); \nhold on\n\nloglog( PSD_u_mean, 'LineWidth', 1.5); \nxlabel(' frequency')\nylabel(' PSD')\nlegend('With Correct Frequency', 'Using Indices Instead of Frequency');\n</code></pre>\n"^^ . . . "Creating internal hyperlinked table of contents through the Word COM in Matlab"^^ . . . . . . . . . . . . . . . . . "2"^^ . . . . "gpu"^^ . . "filter"^^ . "Error in calculating the average values of the rows of a group of excel-files"^^ . "2"^^ . . . "1"^^ . . . . . "Thank you for your comment Cris Luengo. I will try to create minimal reproducible example hereafter. I have found problem finally. lambda optimization pars lambda=lambda*10 and lambda=lambda/10 are stuck and the algorithm repeatedly increase and decrease the lambda. I have changed the code "test_error_norm <= errors_of_epochs(epoch_number,1)" to "test_error_norm <= errors_of_epochs(epoch_number,1)*0.80" and prevent the unnecessary repeated change. Looks like lambda change should be done carefully."^^ . . "<p>I have a matlab toolbox, with a single-window GUI. I was able to build it mcc/deploytool to create a standalone 7MB executable. However, I was not happy for the installer size, as the R2016 matlab runtime is 700MB in size, 100x larger than my application.</p>\n<p>When I saw a new matlab compiler API <code>compiler.runtime.customInstaller</code> coming with R2024b <a href="https://www.mathworks.com/help/compiler/compiler.runtime.custominstaller.html" rel="nofollow noreferrer">is cable of creating smaller MCR installer</a> including only needed files, I was very happy and immediately tried it, however, the result was disappointing.</p>\n<p>The installer bundled with MCR in R2024b for my app build by deploytool - without using the <code>customInstaller</code> - is 1.2GB in size (another 2x increase in size compared to the already large package generated by R2016). Then, when I called</p>\n<pre><code>results = compiler.build.standaloneApplication(&quot;myapp.m&quot;);\ncompiler.runtime.customInstaller(&quot;myapp_installer&quot;, results, 'RuntimeDelivery', 'installer');\n</code></pre>\n<p>however, the generated package has the same 1.2GB in size. I have followed the help page of <code>compiler.runtime.customInstaller</code></p>\n<p><a href="https://www.mathworks.com/help/compiler/compiler.runtime.custominstaller.html" rel="nofollow noreferrer">https://www.mathworks.com/help/compiler/compiler.runtime.custominstaller.html</a></p>\n<p>did I miss anything? why <code>customInstaller</code> fails to trim the installer size? my app only use basic matlab features.</p>\n<p>the <code>requiredMCRProducts.txt</code> file shows that I only need the following MCR components</p>\n<ul>\n<li>'MATLAB Runtime - Core'</li>\n<li>'MATLAB Runtime - Graphics'</li>\n<li>'MATLAB Runtime - Non Interactive MATLAB'</li>\n<li>'MATLAB Runtime - Numerics'</li>\n<li>'MATLAB Runtime - Image Processing Toolbox Addin'</li>\n</ul>\n"^^ . "1"^^ . . "<p>I am trying to implement levenberg marquardt algorithm in matlab but my code doesn't converge and errors keep getting bigger and bigger after first iteration. I checked jacobian table, inverse function and so on but I couldn't figure it out what is the problem.</p>\n<p>I look for the jacobian and calculated both by using numerical differentiation and by calculating partial derivative formulas and calculating by matrix operations.</p>\n<p>I tried build in inverse function and cholesky factorization\nI calculated the matrix and bias calculation, done in the code, with Excel table and formulas and checked the values.</p>\n<p>Code find a low residual error at first bu after calculating jacobian and finding the delta_value and changing the weights in second or third iteration the norm of residuals getting bigger and bigger.</p>\n<p>Is there anything that I can't see?</p>\n<pre><code>clear; clc;\n% Define hyperparameters\nepoch = 10; % Maximum number of epochs\ntol = 0.02; % Tolerance for convergence\nlambda = 0.01; % Initial regularization parameter\nlayer_number = 3; % number of layer(input and output are included)\ninput_size= 1; % Number of input features\nhidden_size = 15; % Number of neurons in the hidden layer\noutput_size = 1; % Number of outputs\nnum_runs = 5; % Number of runs to calculate average\nnumber_of_sample=46; % Number of sample\n\n% Create training data for problem one Sinus wave y = 1/2 + 1/4sin(37pix)\ninput_vals = linspace(-1, 1, number_of_sample)'; % 40 inputs scattered in the interval [-1, 1]\ntarget_vals = 0.5 + 0.25 * sin(3 * pi * input_vals); % Target output according to given formula\n\n% Run the algorithm 5 times for calculating average error to create plot\nerrors_of_epochs_for_average_5_run = zeros(epoch,1); \nfor run = 1:num_runs\n \n W1 = rand(hidden_size,input_size);\n b1 = rand(hidden_size,1);\n W2 = rand(output_size,hidden_size);\n b2 = rand(output_size,1);\n \n parameterVector= [W1(:);b1(:);W2(:);b2]; %parameter vector for jacobian matrix;\n \n\n errors_of_epochs = zeros(epoch,1); % to store error values of each epoch\n for epoch_number = 1:epoch\n % Initialize matrix to store error vectors for each run\n output_vals=zeros(number_of_sample,output_size); %outputs for all samples\n errors_for_each=zeros(number_of_sample,output_size); %error values for each input output value\n \n %forwardpass loop\n for i=1:number_of_sample\n output_vals(i,output_size) = forward_pass(input_vals(i,input_size), W1, b1, W2, b2);\n end\n errors_for_each = target_vals - output_vals;\n error_norm = norm(errors_for_each);\n errors_of_epochs(epoch_number,1) = error_norm; % calculate average sum of square for each epoch\n ***parameterVector= [W1(:);b1(:);W2(:);b2]; % recreate paramVector with new weights***\n Jaco=jacobian(parameterVector, target_vals, input_vals,hidden_size); % calculate jacobian\n\n while true % to calculate delta again when error is bigger than previous one\n \n JTJ=Jaco'*Jaco;\n \n I=eye(size(JTJ));\n JTJ_Lambda_Eye=JTJ+lambda*I;\n JTe=Jaco'*errors_for_each;\n try\n [R,Flag]=chol(JTJ_Lambda_Eye);\n if Flag\n disp('Matrix must be symmetric and positive definite.');\n \n end\n \n % JTJLEyeInverse=inv(JTJ_Lambda_Eye);\n \n L = chol(JTJ_Lambda_Eye, 'lower');\n n=size(JTJ_Lambda_Eye,1);\n I=eye(n);\n Y=zeros(n);\n % Solve for Y using forward substitution\n for i = 1:n\n Y(:, i) = L \\ I(:, i);\n end\n % Now solve L^T * X = Y for X\n JTJLEyeInverse = L' \\ Y;\n catch\n disp('Cholesky factorization failed.');\n break;\n end\n deltaValue=JTJLEyeInverse*JTe;\n parameterVectorTest=parameterVector;\n parameterVectorTest=parameterVectorTest-deltaValue;\n % check wheather the new error create better value.\n W1_test = reshape(parameterVectorTest(1:hidden_size * input_size), hidden_size, input_size);\n b1_test = reshape(parameterVectorTest(hidden_size * input_size + 1:hidden_size * input_size + hidden_size),hidden_size, input_size);\n W2_test = reshape(parameterVectorTest(hidden_size * input_size + hidden_size + 1:end - 1), output_size, hidden_size);\n b2_test = parameterVectorTest(end);\n\n %test delta value whether they are too small for change or not\n if norm(deltaValue)&lt;tol;\n disp(&quot;Parameter changes are too small to continue&quot;);\n break;\n end\n %test feedforward\n test_output_vals=zeros(number_of_sample,output_size);\n for i=1:number_of_sample\n test_output_vals(i,output_size) = forward_pass(input_vals(i,input_size), W1_test, b1_test, W2_test, b2_test);\n end\n\n test_errors_for_each = target_vals - test_output_vals;\n test_error_norm = norm(test_errors_for_each);\n \n if test_error_norm &gt; errors_of_epochs(epoch_number,1)\n lambda=lambda*10;\n % if lambda&gt;1000\n % lambda=1000;\n % end\n else\n break;\n end\n end %finis point of bigger error and increasing lambda\n\n if test_error_norm &lt;= errors_of_epochs(epoch_number,1)\n W1=W1_test;\n b1=b1_test;\n W2=W2_test;\n b2=b2_test;\n lambda=max(lambda/10, 1e-7);\n end\n \n if test_error_norm &lt;= tol\n disp(['Converged at epoch ', num2str(epoch_number), ' in run ', num2str(run)]);\n break;\n end\n\n end\n\n errors_of_epochs_for_average_5_run = errors_of_epochs_for_average_5_run + errors_of_epochs; %to calculate average of 5 run\n\nend\n\n% Plotting the result for investigating\n% Calculate the average error across all runs\navg_epoch_errors = mean(errors_of_epochs_for_average_5_run, 1);\n\n% Plot average error vs. epochs\nplot_target=zeros(number_of_sample ,1);\n for i_test = 1:input_size\n X_test = input_vals(i_test);\n % Forward pass to get the current output\n plot_target(i_test) = forward_pass(X_test, W1, b1, W2, b2);\n % Calculate the current error \nend\nfigure;\nhold on;\n%plot(1:biggest_last_epoch_number, avg_epoch_errors(1:biggest_last_epoch_number), '-o');\nplot(input_vals, target_vals, 'r-o');\nplot(input_vals, plot_target, 'b-o');\nxlabel('Epoch');\nylabel('Average Error');\ntitle('Average Error per Epoch across 5 Runs');\ngrid on;\nhold off;\n\n\n% Define forward pass function\nfunction [outputf,A1] = forward_pass(X, W1, b1, W2, b2)\n Z1 = (W1 * X) + b1; % Linear combination for hidden layer\n A1 = sigmoid(Z1); % Sigmoid activation for hidden layer\n Z2 = (W2 * A1) + b2; % Linear combination for output layer\n outputf = Z2; % Output layer\nend\n% Sigmoid activation function\nfunction cikti = sigmoid(x)\n cikti = 1 ./ (1 + exp(-x));\nend\n\n% Derivative of the sigmoid function\nfunction cikti = sigmoidDerivative(x)\n cikti = sigmoid(x) .* (1 - sigmoid(x));\nend\n\n% Define function for calculating Jacobian\nfunction jaco_return=jacobian(jparameterVector, jtarget_vals, jinput_vals,jhidden_size)\n jaco_return=zeros(length(jtarget_vals), length(jparameterVector));\n W1 = reshape(jparameterVector(1:jhidden_size * 1), jhidden_size, 1);\n b1 = reshape(jparameterVector(jhidden_size * 1 + 1:jhidden_size * 1 + jhidden_size),jhidden_size, 1);\n W2 = reshape(jparameterVector(jhidden_size * 1 + jhidden_size + 1:end - 1), 1, jhidden_size);\n b2 = jparameterVector(end);\n for i=1:length(jtarget_vals) % to creat each line of jacobian for each input output pair\n [~ , jA1] = forward_pass(jinput_vals(i),W1,b1,W2,b2);\n derivW1 = -1 * W2'.* sigmoidDerivative(jA1) *jinput_vals(i); %W1 partial derivatives\n derivb1 = -1 * W2'.* sigmoidDerivative(jA1); %b1 partial derivatives\n derivW2 = -1 * jA1; %W2 partial derivatives\n derivb2 = -1; %b2 partial derivatives linear activation function\n jaco_return(i,:)= [derivW1(:);derivb1(:);derivW2(:);derivb2]; %each line of jacobian matrix \n end\n epsilon=1e-10;\n jaco_test=zeros(length(jtarget_vals), length(jparameterVector));\n jparameterVector_pus=jparameterVector;\n \n for jsatir=1:length(jtarget_vals)\n for jsutun=1:length(jparameterVector)\n outpus_test_normal=forward_pass(jinput_vals(jsatir),W1,b1,W2,b2);\n \n jparameterVector_pus(jsutun)=jparameterVector(jsutun)+epsilon;\n \n W1_test = reshape(jparameterVector_pus(1:jhidden_size * 1), jhidden_size, 1);\n b1_test = reshape(jparameterVector_pus(jhidden_size * 1 + 1:jhidden_size * 1 + jhidden_size),jhidden_size, 1);\n W2_test = reshape(jparameterVector_pus(jhidden_size * 1 + jhidden_size + 1:end - 1), 1, jhidden_size);\n b2_test = jparameterVector_pus(end);\n jparameterVector_pus(jsutun)=jparameterVector(jsutun);\n output_vals_test_plus = forward_pass(jinput_vals(jsatir),W1_test,b1_test,W2_test,b2_test);\n jaco_test(jsatir, jsutun)=((output_vals_test_plus- outpus_test_normal)/epsilon)*-1;\n end\n end\n jaco_return=jaco_test;\nend\n</code></pre>\n"^^ . . . . . . "1"^^ . . "Since you’re summing over the 3rd and 4th dimension after the loop, I would recommend you do that inside the loop and directly build the desired 2D output. Unless the code you posted is not representative and you actually need the 4D output of course."^^ . "0"^^ . "0"^^ . . . "You're right; I apologize for the inconvenience. I have uploaded the Excel file."^^ . . "It does not answer the original question but compiling and running the exe with Matlab 2023a, .NET is not *loaded* by default so it is possbile to change to .NET core."^^ . . "neural-network"^^ . "1"^^ . "0"^^ . "<p>I am trying to patch a color gradient of given angular data</p>\n<p>Here is the data:</p>\n<pre><code>n = [263.6909 287.9987 262.1933 199.6890 128.5683 71.1718 34.6535 15.2568 6.2683 2.4868 0.9872 0.4063 0.1793 0.0876 0.0487 0.0315 0.0241 0.0221 0.0243 0.0319 0.0495 0.0895 0.1838 0.4174 1.0159 2.5605 6.4504 15.6740 35.5053 72.6566 130.6707 201.9328];\n\ntheta=0:(2*pi/32):(2*pi*(32-1)/32);\ntheta(theta&gt;pi) = theta(theta&gt;pi)-2*pi;\n</code></pre>\n<p>I use a patch command</p>\n<pre><code>figure\nhold on\npatch(cos(theta), sin(theta), n, 'EdgeColor', 'none');\nquiver(0,0,-4.6492,-0.9099,0.5,'k','linewidth',3);\naxis equal\n</code></pre>\n<p>** edit start 3/12/2024 **</p>\n<p>The gradient is suppose to be perpendicular to the line between the peak of the concentration and the opposite point along the rim (i.e, from $\\theta(n_{max})$ and $\\theta(n_{max}+\\pi)).</p>\n<p>There are two options I'm trying to apply:</p>\n<p>1.Assuming that there is an exponential decaying gradient where the gradient patch decays from n_max to zero in the vertical direction.</p>\n<ol start="2">\n<li>fitting a Gaussian to the data and use that with a corresponding theta which is segmented equally with respect to the location of the peak (i.e, one of the array point of theta is exactly where the peak is).</li>\n</ol>\n<p>** edit end 3/12/2024 **</p>\n<p>Here in the plot below is what I obtain, and what I wish to obtain</p>\n<p><a href="https://i.sstatic.net/ol5GsSA4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ol5GsSA4.png" alt="enter image description here" /></a></p>\n<p>I highlight that the data is part of a dynamical simulation where the array <code>n</code> changes every iteration, and therefore the gradient slope, and direction, must be according to the given <code>n</code></p>\n"^^ . . "1"^^ . . "<p>there are different ways to add slices. interpolation is definitely not the easiest.</p>\n<p>Firstly, one tool I really like for reading and writing NIfTI files is <a href="https://www.mathworks.com/matlabcentral/fileexchange/8797-tools-for-nifti-and-analyze-image" rel="nofollow noreferrer">Tools for NIfTI and ANALYZE image</a> by Jimmi Shen. It may look a bit old-fashioned compared to the built-in matlab function but I think it gives you a bit more control over the header and the pixel data.</p>\n<p>If you use that toolbox and do</p>\n<pre><code>nii = load_untouch_nii ( '/tmp/MNI152_T1_2mm.nii.gz' ); \n</code></pre>\n<p>then you will have a struct <code>nii</code> with header field <code>hdr</code> and the image field (the pixels) <code>img</code>. This example image has size 91x109x91, you can use <code>interp</code> to sample it to (say) 100x150x100 points:</p>\n<pre><code>[ gx, gy, gz ] = ndgrid ( 1:150, 1:100, 1:100 ); \nimg2 = interp3 ( nii.img, gx, gy, gz, 'nearest' ); \n</code></pre>\n<p>and you can look at the two images:</p>\n<pre><code>figure ( 1 ); imagesc ( nii.img ( :, :, 1 ) ); axis equal \nfigure ( 2 ); imagesc ( rot90 ( img2 ( :, :, 1 ) ) ); axis equal\n</code></pre>\n<p>you can see that the image itself has not changed - you have just added empty space at the sides. (you could have done this by just expanding the matrix!)</p>\n<p>You <em>can</em> also resample your image so that the new image fills the same amount of world space as the old image (in your example only in the <em>z</em>-direction, but <em>x</em> and <em>y</em> is also possible):</p>\n<pre><code>[ gx, gy, gz ] = ndgrid ( linspace ( 1, 109, 150 ), linspace ( 1, 91, 100 ), linspace ( 1, 91, 100 ) );\nimg3 = interp3 ( double ( nii.img ), gx, gy, gz, 'linear' );\nfigure ( 3 ); imagesc ( rot90 ( img3 ( :, :, 1 ) ) ); axis equal\n</code></pre>\n<p>The reason that <code>img3</code> may not be such a good idea is that you have changed the world-size of the image: the original field <code>nii.hdr</code> has a field <code>pixdim</code> which gives the spacing of every point (in this case it is 2x2x2 mm³). But now that you compress the same world-space into more points, their spacing has decreased; you now need to change the header of your resampled file to reflect that (<em>i.e.</em>, the world size of your pixels needs to be smaller).</p>\n<p>Long story short, <code>img2</code> really has slices added to it, <code>img3</code> has been spread over more slices.</p>\n"^^ . . . . "Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking."^^ . . . . "<p>I try to convert a matlab script using spectrogram function to the matplot lib spectrum function.\nOnce converted to a spectrogram grey image, the output images are similar but the Power spectral density matrix shape are different</p>\n<p><strong>Matlab code:</strong></p>\n<p><code>[~,~,~,P] = spectrogram(X, Fs/N, 0, N, Fs, 'centered');</code>\nwith:\nspectrogram(x,window,noverlap,nfft,spectrumtype)\nFs = 50 * 10**6\nnfft = 500</p>\n<p>In that case the shape of P is 500 x 500</p>\n<p><strong>Python code:</strong></p>\n<p><code>P, freq , t, img = plt.specgram(x, NFFT=nfft , Fs=Fs, Fc=Fc, noverlap=0, window = np.hanning(nfft ))</code></p>\n<p>In that case the shape of P is 500 x 100000</p>\n<p>Looks like the window parameters from matlab allows to divide the signal into segments and has nothing to do with the window parameter of plt.specgram (as per the documentation actually ;) )</p>\n<p>My question is: how to produce a 500x500 matrix using plt.specgram ?\nAny idea ?\nThank you !</p>\n"^^ . . . "1"^^ . . "0"^^ . . . . . "permutation"^^ . "1"^^ . . . . . . . . . . "0"^^ . . . "0"^^ . . "0"^^ . . "2"^^ . "How to add slices to a MRI image? (interpolation)"^^ . "1"^^ . . "0"^^ . "0"^^ . . "0"^^ . . "<p><a href="https://i.sstatic.net/JpcAF9T2.png" rel="nofollow noreferrer">enter image description here</a><a href="https://i.sstatic.net/treNwxry.png" rel="nofollow noreferrer">enter image description here</a>\nI am working on the IEEE 34-bus distribution network using MATLAB Simulink. I am using the system provided in the link below:</p>\n<p>&quot;https://www.mathworks.com/matlabcentral/fileexchange/123220-ieee-34-bus-distribution-feeder-discrete-simulink-model?s_tid=srchtitle_support_results_1_ieee%2034&quot;</p>\n<p>When I try to perform load flow analysis for the model, the results appear to get stuck at the bus associated with the voltage regulator. As a result, I cannot obtain load flow results for all the buses.</p>\n<p>What might be causing the issue with the voltage regulator in the simulation?\nAre there any specific settings or adjustments required for the voltage regulator to enable successful load flow analysis?</p>\n<p>Any guidance or suggestions to resolve this issue would be greatly appreciated.</p>\n"^^ . . "2"^^ . . . . . . "0"^^ . "Thank you so much! I just got it working! I'm just a student, and this is our first semester using Simulink, so I didn't even know that some of these blocks existed."^^ . . . "hypothesis-test"^^ . . "It works, many thanks!"^^ . . . . "0"^^ . "@CrisLuengo From what I understand, all of the rows labeled `202211` in column 1 are assigned to be aggregated type **1**, except for the **third** instance, which is assigned to type **2**. Similarly for rows labeled `202212`, and so on."^^ . . "<p>I have a large Simulink model consisting of several subsystems, piping sections for example. Each subsystem is modeled with a m-function. Within the m-function I throw warnings (for now I use matlab warnings but I could only print the information) when specific conditions occur in the pipings.</p>\n<p>I would like to trace the warning message to the full path of the block calling the m-function, in order to inform the user of which piping is causing the trouble. I have tried using <code>gcb</code> in my m-functions but it is not supported by the code generation capabilities of Simulink, which I need.</p>\n<p>Is there another approach to get the whole trace of a warning in this use case ?</p>\n"^^ . "MATLAB unittest: set variable and use it across all test method in one test class"^^ . "Data would also be nice ;)"^^ . "0"^^ . . . . . "<p>I am trying to find a way to tune the parameters of controllers with variable structure for power systems using Matlab and simulink. I would like to find a method where it is not needed to simulate the environment to tune the parameters. For now I use the minimization of the H2 or the H-infinity norm of the system. I am currently trying to tune the parameters of a simple PID controller for a second order plant (G(s) = 1 / (s^2 + 10s + 20)). The model is depicted below :</p>\n<p><a href="https://i.sstatic.net/XI23B7jc.png" rel="nofollow noreferrer">model</a></p>\n<p>I have tried to use particle swarm optimization to minimize H2 or H-infinity norm of the transfer function :</p>\n<p>T(s) = G(s) / (1 + C(s)G(s))\nwhere G(s) is the transfer function of the plant and C(s) = Kp + Ki/s + Kd*s</p>\n<p>The problem that I have is that the optimization return very large parameters (the order of magnitude of the gains is between 10^10 and 10^14) that lead to a non-ideal behvior.</p>\n<p>For comparison this is the resulting behavior when optimizing with the norms:</p>\n<p><a href="https://i.sstatic.net/jyaNPXaF.png" rel="nofollow noreferrer">norm</a></p>\n<p>And this is the resulting behavior when optimizing with simulation :</p>\n<p><a href="https://i.sstatic.net/TQSQoiJj.png" rel="nofollow noreferrer">simulation</a></p>\n<p>The value of the H2 and H-infinity norms with the resulting parameters are very low while the resulting behavior is really oscillatory.</p>\n<p>Thank you,</p>\n"^^ . . . "Matlab object arrays' method call equivalent in Python"^^ . "<p>There are many solutions for your immediate problem, but in general you cannot translate syntax 1-to-1 from one language to another. Each language has its own syntax and its own peculiarities.</p>\n<p>In MATLAB, <code>A.toClass2()</code> and <code>toClass2(A)</code> both call the same function. The second syntax you can directly translate to Python by writing a free function (i.e. not a class method) that does something different depending on the type of the input.</p>\n<p>A different alternative is to not create lists of your object in Python, but to have an object contain a list with the data (or create a class that contains a list of your objects). Then you can customize methods working on that object.</p>\n"^^ . . "0"^^ . . . . . . "1"^^ . . . . "0"^^ . "4"^^ . . . "psychtoolbox"^^ . . . . . . . "0"^^ . . . "0"^^ . . "1"^^ . "1"^^ . "1"^^ . . "0"^^ . . "0"^^ . . "<p>I generate a Simulink model programmatically which means that I change the name of the signals at bus selector inports.</p>\n<p>In order to reconfigure the bus selector after programmatically changing the model I get all input signals from the <code>Bus Selector</code> block, join the signal names and provide them again to the <code>Bus Selector</code> output :</p>\n<pre><code>list_input_signals = get_param(bus_selector_handle,'InputSignals');\ninput_signals_str = strjoin(list_input_signals , ',');\nset_param(bus_selector_handle,'OutputSignals',input_signals_str )\n</code></pre>\n<p>This is based on an answer on Mathwork's forum here : <a href="https://fr.mathworks.com/matlabcentral/answers/772493-select-bus-elements-programmatically" rel="nofollow noreferrer">https://fr.mathworks.com/matlabcentral/answers/772493-select-bus-elements-programmatically</a></p>\n<p>It works but the <code>get_param</code> instruction is painfully slow. It is taking up 99% of the execution time of the three lines according to Matlab's profiler. It represents around 15s for 250 bus selector blocks and it scales too much for bigger models.</p>\n<p>Is there a more efficient way to refresh the <code>Bus Selector</code> block or to access all input signals to replace the incrimated <code>get_param</code> ?</p>\n<p>I tried the following workaround but with the same issue :</p>\n<pre><code>ph = get_param(bus_selector_handle, 'PortHandles');\nsh = get_param(ph.Inport, 'SignalHierarchy');\ninput_signals_str = strjoin({sh.Children.SignalName},',');\nset_param(bus_selector_handle,'OutputSignals',input_signals_str )\n</code></pre>\n"^^ . . "<p>I have a Matlab file containing an array of datetime objects with 18750 timestamps.</p>\n<p><a href="https://i.sstatic.net/B2DY8Wzu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/B2DY8Wzu.png" alt="enter image description here" /></a><a href="https://i.sstatic.net/itdSip0j.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/itdSip0j.png" alt="enter image description here" /></a></p>\n<p>When I use scipy.io to import the data, it gives the following output which is very different.</p>\n<p><a href="https://i.sstatic.net/TM66dzzJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TM66dzzJ.png" alt="enter image description here" /></a></p>\n<p>I am expecting an array of timestamps just like what is seen in Matlab. Any idea how I can achieve this? Thank you very much for your time and attention.</p>\n"^^ . . "0"^^ . . "<p>I'm trying to locate the file in the Matlab installation or per-user configuration in which the path to the Java JDK is stored.</p>\n<p>I tried changing the JDK path via <code>jenv</code> and then looking for a recently-modified file (via <code>find . -type f -mtime -1</code>) but the only files found by that test do not seem to contain the Java JDK path.</p>\n<p>The bigger picture is that I am running Matlab in a Docker container (see <a href="https://hub.docker.com/r/mathworks/matlab" rel="nofollow noreferrer">this web page</a> about that) and I am trying to create a persistent configuration for the Java JDK. I can change the JDK location via <code>jenv</code> when Matlab is running in a Docker container, but that change is forgotten after exiting and relaunching Matlab.</p>\n"^^ . . . . . . "How MATLAB makes the distinction between P-Cores and E-Cores?"^^ . . . . . . . "<p>I'm new to Matlab and I'm trying to write a code that draws these two curves in polar coordinate system and colors the area bounded by them.</p>\n<p><strong>r1 = 3 * sin(theta)</strong></p>\n<p><strong>r2 = 1 + sin(theta)</strong></p>\n<p>I've tried several preliminary methods, but to no avail.</p>\n<p>I'm using Matlab R2022b</p>\n"^^ . . . . . . . "0"^^ . . . "The only time you need to apply `fftshift` is for visualization. Somehow people prefer to look at the frequency range -N/2 to N/2 rather than 0 to N-1. But this is just our preference, any computations you do are not concerned with this. Don’t think of `fftshift` as rearranging the FFT output, but rather as shifting the window over which we look at the periodic frequency domain."^^ . . "1"^^ . . . "@jarhead The data you presented doesn't represent a smooth gradient in any direction - do you want us to infer the vector angle from the data and then generate the gradient? Or smooth out the vector `n` via interpolation? Or can you just return the vector direction from whatever process makes `n`? It's not clear from your question where you got `-4.6492,-0.9099` from for the quiver..."^^ . . . "@ShivamMishra the OP of the other post is mistaken, he also has a TimeStamp object"^^ . "Please define clearly what you mean by "It gives wrong result", you should provide a [mre] with input and output data for this function only, if that is where you think the error is."^^ . . "architecture"^^ . . . . . "Thanks, I just discovered that. You should have written that as an answer."^^ . "0"^^ . "0"^^ . . . "@CrisLuengo This case is a bit simpler because there is only one color per column in the sample image. \nKostas, your image doesn't seem to have an alpha channel. How did you want to handle that?"^^ . . . . . . . . . . "0"^^ . "0"^^ . . "breakpoints"^^ . "Thank you for this comment. I'm editing my question now. In principle, the axis of polarization (indicated by the vector, black arrow) is not necessarily identical to the direction of the gradient. So perhaps what that I am asking here is why the patching of the gradient (given the distribution along the rim is not symmetric). I thing the problem lies with the fact that the data I have is not symmetric around the angle segmentation, but even if I interpolate and take N to be very large (such that the intervals between the angles is small) I still obtain a messed-up color patch."^^ . . . . "1"^^ . . . . "1"^^ . "I just discovered, that there is also a hybrid method, which is basically a multistep-Runge-Kutta (called Runge-Kutta-Nyström). As I understand it, it needs N ode-evals to achieve order N (maybe +/- 1). But it should be more stable than the Adams-methods at higher stepsizes. Can someone tell me, what increase in stepsize one can expect (if that is possible)? Say I do 5 ode-evals/order 5. Stability aside, RKN would have to permit a 5 times bigger stepsize to compete with Adams efficiency-wise..."^^ . . "0"^^ . "1"^^ . "<p>I have a data set, FR. I am trying to plot the confidence levels for the same but I am encountering a warning message :&quot;Warning: Equation is badly conditioned. Remove repeated data points or try centering and scaling.&quot;. I don't know what is the issue as well as how to solve it. Any kind of help will be very useful. I am getting a graph like this (as shown below) but I think this <a href="https://i.sstatic.net/OlDkGNF1.png" rel="nofollow noreferrer">enter image description here</a></p>\n<pre><code>%Create fit and confidence interval\n FitVec = fit(freq_tl,T121,'poly9')\n pRvecConf = predint(FitVec,freq_tl,0.95,'observation','off');\n \n %get the fitting values\n fitY=feval(FitVec,freq_tl);\n %multiply the confidence interval with sqrt(xVec(i)).^2 .*xVec'\n ci=(fitY-pRvecConf(:,1));\n %get the weighted confidence interval\n Conf_new=[fitY-ci,fitY+ci];\n %Plot\n figure\n plot(FitVec,freq_tl,T121) \n hold on\n plot(freq_tl,Conf_new,'m--')\n legend('Data','Fitted curve','Confidence','Location','se')\n xlabel('Length')\n ylabel('Strength')\n\n</code></pre>\n"^^ . . . . . "It could be, but i'd like to rather keep 1 check (obj creation, obj creation inside it, obj deletion from it, obj deletion) per the lowest test level. I assume, function with testCase parameter is the lowest here, and there are no subtests or substeps or something like this?\nExcept global variables, the idea is to read id as input parameter and then add some teardown-like method, that will update input parameters with any test data that is created by passed test, so then next one can use setup with updated data to use them"^^ . . . "0"^^ . . . . . "Matlab mldivide returns NaN when there are multiple solutions"^^ . . . . . . . . . . . . . . "How to Run Compiled MATLAB Executable Without MATLAB Installed?"^^ . . . . "python"^^ . "0"^^ . "0"^^ . "compiler.runtime.customInstaller fails to reduce mcr installer size"^^ . . . . "...*Without* the backslash-h, I get hyperlinks from the *page numbers in the TOC* to the headings when working in Word, but not when exported to PDF. I suspect that this property is described as having an effect when the document is "saved to the Web" (i.e.HTML) and that may have had an effect at one time. Not sure it does now, but it may be affected by other "save to web" settings."^^ . . . "1"^^ . . . . "0"^^ . "0"^^ . . . . . "1"^^ . "<p>I'm trying to install MATLAB 2024a on a Ubuntu 22.04 LTS system. The system is behind a proxy which requires configuring a proxy and adding a CA Certificate.</p>\n<p>For whatever reason, MATLAB does not seem to use the system's certificate store. There is a place where I can configure a proxy but I cannot find anywhere where I can add/configure a certificate. Therefore, when I click &quot;test connection&quot;, it will fail. When I try anything that accesses the internet (documentation, install addon, etc), I get a certificate error.</p>\n<p>I contacted support and they tell me they don't support that or any SSL interception. They tell me to use offline installers and manually goto mathworks for documentation. I find this hard to believe that all the corporations around the world that have proxies that require a certificate are doing this with MATLAB. Also, on the windows computers (behind the same proxy), it works fine.</p>\n<p>Googling, I found an old solution of using keytool to add to the java keystore but that doesnt seem to work anymore.</p>\n<p>Does anyone know of a way to resolve this? For example, firefox does its own thing but has a plugin to make it work.</p>\n"^^ . . "circuit"^^ . "1"^^ . "0"^^ . . . . . . "0"^^ . "As I understand it, in this function the power generation of the generators is not fixed. But I want to pass a fixed power generation and see, if there's a power flow possible (adhering to the branch limits) with the given settings. Is Matpower not able to do that?"^^ . . . . . "0"^^ . . . . . . . . . "0"^^ . "0"^^ . . . "1"^^ . . "1"^^ . "1"^^ . . "<p>Less than 10 minutes after posting this I was able to finally detect the source of the weird error: for some reason, and only on certain loop conditions, MATLAB would report a number in the cell yp with some numerical round-off, reporting it as 35.0 for example instead of 35. This would cause the hygepdf to return a null value, because it can only work with integers, hence the screw up. The solution was to use a rounding function on yp, and this line fixed it:</p>\n<pre><code> yv{j} = round(yp(fin)); \n</code></pre>\n<p>I'll leave this up here in case anyone else has similar problems, but cannot explain why it only had those round up errors with certain loop iterations and not with others!</p>\n"^^ . "0"^^ . "MATLAB Programmatic App Fcn Callback not working"^^ . . . "@Wolfie I added two photos , If you need more explanation ,you can tell me"^^ . "@CrisLuengo For my purposes, I don't need the output of the loop calculation results. All individual wave harmonics are calculated in the loop. Accordingly, they depend on four variables: frequency, angle of direction and two coordinates - therefore, the array is four-dimensional. To get the final desired result - a surface waving, I perform a double summation of the frequencies and angles of all harmonics. However, I have not figured out how to do as you advised. Do the summation through a loop, thereby adding another outer loop in addition to the main one? Or something else?"^^ . . . . . . . . . . . . "Thank you for your response.\nI tried this code because the use of GPU is separate in the matlab fft2 code description.\nIf I use GPU instead of CPU when processing large-capacity images, wouldn't it be faster? I tried it with the thought, but I didn't know that there would be a small difference in speed between CPU FFT and GPU FFT.\nThank you for the good insight."^^ . "polar-coordinates"^^ . . "<p>Thanks to beaker's advices I was able to devise this:</p>\n<p>inputs:</p>\n<ul>\n<li><code>Map</code>: Matrix containing label values. Can be double, int, char.</li>\n<li><code>K</code>: Maximum count of values for <code>colormap()</code>. Chosen to match K-colour algorithm below.</li>\n<li><code>Distance</code>: Diameter of neighbourhood scanning for adjacent regions.</li>\n</ul>\n<h2>0. ensure the label are consistent</h2>\n<pre><code>Labels = unique(Map);\nfor ii = 1 : N\n Map(Map == Labels(ii)) = ii;\nend\n</code></pre>\n<h2>1. Matrix to Graph</h2>\n<p>Preallocate adjacency matrix. Loop over all &quot;grains&quot; dilate them (to overflow to their neighbours). Exclude <code>0</code> from the list (Labels outside the neighbourgood are zeroed). Fill row in adjacency matrix. Finally zero diagonal in the matrix - eliminate self-adjacency.</p>\n<pre><code>Graph = false(N);\n\nfor ii = 1:N\n Grain = imdilate(Map == ii, strel('disk', Distance));\n Neighbours = unique(Map .* Grain);\n Neighbours = Neighbours(Neighbours ~= 0);\n Graph(Neighbours, ii) = true;\n Graph(ii, Neighbours) = true;\nend\n\nGraph = Graph &amp; ~eye(size(Graph))\n</code></pre>\n<h2>2. Use modified <a href="https://www.cs.princeton.edu/%7Eappel/Color.pdf" rel="nofollow noreferrer">Kempe's K-colour algorithm</a></h2>\n<h4>2.1. Preallocate working variables</h4>\n<p>Preallocate <code>Stack</code> variable to keep trace of nodes removed form the graph, <code>Pruned</code> to keep 'pruned' graph, <code>Pool</code> to keep 'active' nodes and <code>Codes</code> to store 'Colour codes'.</p>\n<pre><code>N = numel(Labels);\nStack = nan(N, 1);\nPruned = Graph;\nPool = 1 : N;\nCodes = nan(1, N);\n</code></pre>\n<h4>2.2. Dismantle the graph</h4>\n<p>Find node with least neighbours, put its index on stack and delete it from adjacency matrix (prune it). Repeat with pruned adjacency matrix until last node is on the stack and adjacency matrix is empty.</p>\n<pre><code>for ii = 1 : N\n Degrees = sum(Pruned);\n [~, idmin] = find(Degrees == min(Degrees), 1);\n [~, Pruned] = pop(Pruned, idmin);\n Stack(ii) = Pool(idmin);\n [~, Pool] = pop(Pool, idmin);\nend\n</code></pre>\n<h4>2.3. ('Reassenble' the graph) and assign codes</h4>\n<pre><code>for ii = N : -1 : 1 % Start with last node in the stack\n % Read colour codes of neighbouring nodes. `NaN` returned for nodes still on stack* \n NgbCodes = Codes(Graph(Stack(ii), :));\n % Check count of codes used in neighbouring nodes.\n if sum(~isnan(unique(K))) &lt; Ncolours\n % If lower than number of codes, find the unused codes\n ColorPool = setdiff(CodeList, NgbCodes);\n % Assign the first unused code to the node\n Codes(Stack(ii)) = ColorPool(1);\n else\n % If all codes are used, leave unassigned (let user increase K and try again)\n end\nend\n</code></pre>\n<h2>3. Apply the codes to the matrix</h2>\n<pre><code>Map = Codes(Map);\n</code></pre>\n<h2>Nested functions</h2>\n<p>Both functions pop <code>rc</code>-th element, or column, respectively, from matrix or vector.</p>\n<pre><code>function [CLMN, B] = prune(A, rc)\n CLMN = A(:, rc);\n B = A([1 : rc - 1, rc + 1 : end], :);\n B = B(:, [1 : rc - 1, rc + 1 : end]);\nend\n\nfunction [Val, B] = pop(A, rc)\n Val = A(rc);\n B = A([1 : rc - 1, rc + 1 : end]);\nend\n</code></pre>\n<hr />\n<p>Modifications in the algorithm described in linked presentation, page 9:</p>\n<ul>\n<li>I do not look for (any) node with Degree <code>D &lt; K</code>, I look for node with lowest degree (no matter how related to K). If <code>D &lt; K</code> is valid for at least one node, it is found. If such node does not exist (easy for K=3) the branches do not differ significantly.</li>\n<li>I don't use recursive call, stack and other variable sizes are determined in the beginning and they only shrink.</li>\n<li>Condition for neighbouring colour codes assigned count <code>NC &lt; K</code> is automatically <code>true</code> for <code>D &lt; K</code> - no need for such check then.</li>\n</ul>\n"^^ . . . . "Matlab Warning: Equation is badly conditioned. Remove repeated data points or try centering and scaling"^^ . . "Can you produce maybe a small example with code that demonstrates the issue and post that? It is hard to advise you unless we see exactly how you scaled the problem and how large the differences are and how fast they are growing."^^ . . . "1"^^ . "2"^^ . . "0"^^ . . . . "0"^^ . . "mcc"^^ . "@beaker it's not particularly nice looking or efficient, but you can get the run-lengths with `arrayfun(@(x)1+x-find([NaN,m(1:x)]~=m(x),1,'last'),1:numel(m));` to replace that loop. Albeit arrayfun is basically a loop anyway..."^^ . . . "1"^^ . . . . . "0"^^ . . . . . . "2"^^ . . "0"^^ . "<p>I've developed simulink model like below:\n<a href="https://i.sstatic.net/bTh0NfUr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bTh0NfUr.png" alt="enter image description here" /></a></p>\n<p>In the model there is slider gain which can be adjusted in range from 0 to 1.</p>\n<p>I'd like to update Scope:</p>\n<p><a href="https://i.sstatic.net/GsYLk6wQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GsYLk6wQ.png" alt="enter image description here" /></a></p>\n<p>when slider gain is adjusted:</p>\n<p><a href="https://i.sstatic.net/nZY5T8PN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nZY5T8PN.png" alt="enter image description here" /></a></p>\n<p>I've watched the video where it worked by default. Lecturer just set up in Scopes options, Time range from 0 to 0.04 and it did update. In my model it doesn't work. How to achieve such reactive simulation?</p>\n"^^ . "<p>I need help coding Direct Sequence Spread Spectrum into my Binary Phase Shift Keying Code. DSSS is the main piece of my objective. The code provided is composed of Binary Information, Carrier Wave, BPSK, AWGN, Impulse Noise.</p>\n<pre><code>clc;\nclear all;\nclose all;\n\nN = 7;\nI = randi([1], 1, N);\nI = [1 0 1 0 1];\n\nfor V = 1:length(I) %Binary Phase\n if I(V) == 1\n nn(V) = 1;\n else\n nn(V) = -1;\n end\nend\n\ni = 1;\nt = 0:0.0001:length(I);\nfor j = 1:length(t)\n if t(j) &lt;= i\n y(j) = nn(i);\n else\n i = i + 1;\n end\nend\n\nFc = sin(2 * pi * 2 * t);\nx = y .* Fc;\n\n% AWGN Noise\nSNRdB = 10; % Adjust SNR as needed\nsnr_lin = 10^(SNRdB / 10);\nnoise_variance = 1 / snr_lin;\nnoise = randn(size(t)) * sqrt(noise_variance);\nAWGN = x + noise;\n\n% Impulse Noise Parameters\nimpulse_amplitude = 10; % Adjust the amplitude as needed\nimpulse_prob = 0.01; % Probability of an impulse at each time index\nimpulse_noise = zeros(size(t));\nimpulse_indices = rand(size(t)) &lt; impulse_prob;\nimpulse_noise(impulse_indices) = impulse_amplitude;\nIMPULSE = x + impulse_noise;\n\n\nsubplot(5, 1, 1);\nplot(t, y);\naxis([0, length(I), -2, 2]);\nxlabel('Time');\nylabel('Voltage')\ntitle('Transmitted Binary Information');\n\n\nsubplot(5, 1, 2);\nplot(t, Fc);\naxis([0, length(I), -2, 2]);\nxlabel('Time');\nylabel('Voltage');\ntitle('Carrier Signal');\n\n\nsubplot(5, 1, 3);\nplot(t, x);\naxis([0, length(I), -2, 2]);\nxlabel('Time');\nylabel('Voltage');\ntitle('BPSK');\n\nsubplot(5, 1, 4);\nplot(t, AWGN);\naxis([0, length(I), -2, 2]);\nxlabel('Time');\nylabel('Voltage');\ntitle('BPSK with AWGN Noise');\n\nsubplot(5, 1, 5);\nplot(t, IMPULSE);\naxis([0, length(I), -2, 2]);\nxlabel('Time');\nylabel('Voltage');\ntitle('BPSK with Impulse Noise');\n</code></pre>\n<p><a href="https://i.sstatic.net/2fVOZPnM.png" rel="nofollow noreferrer">BPSK PLOT IMAGE</a></p>\n<p>I did try to code DSSS into the BPSK code along with the AWGN and Impulse Noise but results got errors, and no visible outputs in its plots or graphs.</p>\n"^^ . . . "0"^^ . . "1"^^ . "<p>I generated filter coefficients with scipy's signal.butter to use in real time filtering in Arduino, and I'm validating the filter with a simple Matlab code that produces a dummy wave and produces a filtered wave from it.</p>\n<p>I validated the scipy generated coefficients for a 1st order filter, but when doing 4th order the filter seems to become unstable, which makes no sense. I think it's a logic issue either on the math side, or the interpreting the coefficients side, but maybe it's a code issue.</p>\n<p>Scipy generates 9 denominators (a0 to a8) and 5 numerators (I'm assuuming b0 to b4) but the matrix for b has the following format: [ 4.82121714e-13 0.00000000e+00 -1.92848686e-12 0.00000000e+00\n2.89273028e-12 0.00000000e+00 -1.92848686e-12 0.00000000e+00\n4.82121714e-13]\nIn the first order validation I simply ignored the 0s, and assumed the third value to be b1, so I've been doing the same, assuming the non-0 values to be b0-b4. When running the code for 1st order the signal gets filtered (commented part of the code), but when doing it for 4th order it explodes (uncommented part of the code).</p>\n<p>Matlab code</p>\n<pre><code>% --------- Data Señal de entrada\nFs = 20000; % frecuencia de muestreo (o cuantas muestras por segundo) (Hz)\nT = 1/Fs; % periodo de muestreo (o delta t por muestreo) (s)\nL = Fs; % Longitud de señal, L=Fs para ser 1 segundo\nt = (0:L-1).*1/Fs; % vector de tiempo (s)\nf = 10; % frecuencia señal de entrada (Hz)\nx = sin(2.*pi.*f.*t) + 0.1*sin(2*pi*1000*t) + 0.1*sin(2*pi*5000*t); % señal de entrada con ruido\n\n% -------- cutoff frecuencias, wc = 1/RC = 1/tao; wc = 2*pi*fc = 1/tao\nfcLPF = 13;\nfcHPF = f^2/fcLPF;\ntao1 = 1/(2*pi*fcHPF);\ntao2 = 1/(2*pi*fcLPF);\n\n% -------- coeficientes, Band-pass 4to° orden\na0 = 1;\n\n% a1 = -1.99832407;\n% a2 = 0.99833393;\n\na1 = -7.99560326;\na2 = 27.96927189;\na3 = -55.90796275;\na4 = 69.84684949;\na5 = -55.84709416;\na6 = 27.90840316;\na7 = -7.96951656;\na8 = 0.99565219;\n\n% b0 = 0.00083304;\n% b1 = -0.00083304;\n\nb0 = 4.82121714/10000000000000;\nb1 = -1.92848686/1000000000000;\nb2 = 2.89273028/1000000000000;\nb3 = -1.92848686/1000000000000;\nb4 = 4.82121714/10000000000000;\n\n\n\n% ------- Algoritmo filtro Band-pass\ny = zeros(1,length(t));\n\nfor n=9:length(t)\ny(n) = - a1/a0*y(n-1) - a2/a0*y(n-2) - a3/a0*y(n-3) - a4/a0*y(n-4) - a5/a0*y(n-5) - a6/a0*y(n-6) - a7/a0*y(n-7) - a8/a0*y(n-8) + b0/a0*x(n) + b1/a0*x(n-1) + b2/a0*x(n-2) + b3/a0*x(n-3) + b4/a0*x(n-4);\n\n% for n=3:length(t)\n% y(n) = - a1/a0*y(n-1) - a2/a0*y(n-2) + b0/a0*x(n) + b1/a0*x(n-1);\n\nend\n\n% ------- figuras\nfigure;\nhold on\nplot(t,x,&quot;k&quot;)\nplot(t,y,&quot;r&quot;,&quot;LineWidth&quot;,2)\nylabel(&quot;Amplitud de Señales&quot;)\nxlabel(&quot;Tiempo [seg]&quot;)\nlegend(&quot;Señal Original&quot;,&quot;Señal Filtrada&quot;)\nbox on\nhold off\n</code></pre>\n<p>I don't think it's an issue, but here's the python code I used, I'm running it on collab</p>\n<pre><code>import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nfrom scipy import signal\n\nbt,at= sp.signal.butter(4,[7.692307692307693,13],'bandpass',fs=20000)\nb1,a1= sp.signal.butter(1,[7.692307692307693,13],'bandpass',fs=20000)\n</code></pre>\n"^^ . "This is relevant but doesn't really answer the question of *how*. For example, it doesn't tell us what would happen on a CPU with only E-cores, no P-cores, like Alder Lake N, or Xeon 6 Sierra Forest. Or a VM that had only E cores on a normal desktop. Or if run on hypothetical future machines with different kinds of P and E cores, whether it would still detect the E cores as E cores. (Like on AMD where their Zen4c cores are just Zen4 but with smaller cache and tuned for lower max clock speed.)"^^ . . . "2"^^ . "0"^^ . . . "Error: Operator '>' is not supported for operands of type 'cell'."^^ . "0"^^ . "I think the output produced by Matlab is correct. Note that using the numerical version of `rref` (with some number instead of `h`) gives the same result. From [Wikipedia](https://en.wikipedia.org/wiki/Row_echelon_form#Reduced_row_echelon_form): (a) the leading entry in each nonzero row must be `1`; and (b) each column containing a leading `1` must have `0` in all its other entries. According to (a), the leading entry of the second row must be `1`, not `3-2*h`. Also, from (b), entry (1,2) must be `0`, not `h` as you expected"^^ . . "0"^^ . "emphasize neighbouring regions in matlab"^^ . "1"^^ . . . "<p>To add DSSS to your BPSK signal, you have to combine your data signal with a higher data-rate bit sequence (or code). Before you apply the tone you have to multiply your BPSK signal by the code, below I show a code for a chip rate (the ratio between code and data rates) of 10:</p>\n<pre><code>clc;\nclear all;\nclose all;\n\nN = 7;\nI = randi([1], 1, N);\nI = [1 0 1 0 1];\n\nfor V = 1:length(I) %Binary Phase\n if I(V) == 1\n nn(V) = 1;\n else\n nn(V) = -1;\n end\nend\n\ni = 1;\nt = 0:0.0001:length(I);\nfor j = 1:length(t)\n if t(j) &lt;= i\n y(j) = nn(i);\n else\n i = i + 1;\n end\nend\n\n%% DSSS\nM = 10;\ncode = randi([0 1], 1, M);\n\ncode_nn = code*2-1;% Binary phase\n\n% Code length = 1 BPSK symbols\ncode_y = repmat(code_nn, round(length(y)/length(I)/M), 1); \ncode_y = code_y(:).';\n\ncode_y = repmat(code_y, 1, length(I));\n\n% DSSS signal\ny_dsss = y(1:length(code_y)).*code_y;\n\n%%\nFc = sin(2 * pi * 2 * t);\nx = y .* Fc;\n</code></pre>\n<p>Also, I recommend you to use <code>repmat</code> and similar function to create the Binary phase and the <code>y</code> signal, it will be faster. Just check the way I did for the code signal.</p>\n"^^ . "3"^^ . . . . "2"^^ . . . "1"^^ . . . . . "function"^^ . . . . "0"^^ . . . . . . . . . . . . . "equation"^^ . . "0"^^ . "0"^^ . . . . . . . . . "mask"^^ . . . "0"^^ . . . . "About a `jenv` command in `startup.m`, the difficulty I see is that Matlab always says to restart in order for the changes to take effect, so just putting `jenv` won't make the change available in that same session. (As I was saying, the Docker image seems to make a clean start each time, so it doesn't know about changes in a previous session.)"^^ . . "Controller parameters tuning without simulation"^^ . "0"^^ . "I'm pretty sure MATLAB requires you to pass either `float`s or `double`s, i.e. single/ double precision floating point numbers. At least all the examples I've seen use `double` arrays, the error message also points in that direction."^^ . . . "0"^^ . "1"^^ . "postgresql-14"^^ . "How can I display a vector and a matrix repeatedly when using fprintf"^^ . . . . "<p>I need to store some really tiny positive and negative numbers in Matlab. One way is to store their signs separately, and the log10 of their magnitude, which lets me store numbers as small as 10^(-<code>realmax</code>)=10^(-10^308), effectively in double precision.</p>\n<p>But is there a way to use Matlab's <code>sym</code> and <code>vpa</code> to store numbers as small as this, with the magnitude and sign together, not separately, such that later I can extract their sign, and their order of magnitude, i.e. log10 of their absolute value, in double precision?</p>\n<p>I tried something like <code>x=sym('-10^(-1e308)')</code>, but this produces an error.</p>\n"^^ . . . . . "Adams-Bashforth coefficients"^^ . . . "Is this what you are looking for? https://stackoverflow.com/questions/51158078/load-stl-file-in-matlab-and-convert-to-a-3d-array/51158671#51158671"^^ . . . . . . . "0"^^ . . "0"^^ . . "timestamp"^^ . . . . "<p>You could use the <code>diff</code> (difference vs the previous sample) of the months array to look for when it changes, i.e. where the diff is non-zero. Then you <code>find</code> these indices and add two to them to offset by 2 weeks.</p>\n<pre><code>idx = find([true; diff(m)~=0])+2;\n</code></pre>\n<p>If you want to generate the 2nd column in your example then the full code would look something like</p>\n<pre><code>% Example input data\nm = [202211, 202211, 202211, 202211, 202211, 202212, 202212, 202212, 202212];\n\n% Find indices where month changes, offset by two weeks.\n% First sample is always true as we want to count the first week in the input\n% and &quot;diff&quot; returns an array one element shorter than the input\ndm = find([true; diff(m(:))~=0])+2;\n\n% Create an output with type &quot;1&quot; as the default and &quot;2&quot; for the 3rd-week indices\ndm( dm &gt; numel(m) ) = []; % Handle edge case where the offset exceeded the array size\naggType = ones(size(m));\naggType(dm) = 2;\n</code></pre>\n<hr />\n<p>Prompted by @beaker's comment, here's a way to do it with a simple loop which keeps track of how many consecutive equal values there are for each sample, and then finds the corresponding indices by checking if the count equals 3. This is more robust to inputs which might not have 3 consecutive values the same in each batch.</p>\n<pre><code>% Trickier input with &lt;3 samples for some values, inc. at start\nm = [202210, 202210, 202211, 202211, 202211, 202211, 202211, 202212, 202212, 202212, 202212, 202301, 202301, 202302, 202302, 202302];\n\nN = ones(size(m));\nfor ii = 2:numel(N)\n if m(ii) == m(ii-1)\n N(ii) = N(ii-1) + 1; % another consecutive equal value\n else\n N(ii) = 1; % reset the counter, value changed\n end\nend\n\naggType = ones(size(m));\naggType( N==3 ) = 2; % N==3 are the desired samples\n</code></pre>\n"^^ . . . "I used something similar with python pyATS framework, when complex E2E scenario was incorporated in one class with test methods as steps of its scenario with own checks. Although it isn't a unit test framework, so allow much more flexibility in different test structure approach."^^ . "integral"^^ . . . . "<p>So today I finally understood what is the purpose of the <code>fftshift</code> function found in both <a href="https://www.mathworks.com/help/matlab/ref/fftshift.html" rel="nofollow noreferrer">Matlab</a> and <a href="https://numpy.org/doc/stable/reference/generated/numpy.fft.fftshift.html" rel="nofollow noreferrer">Numpy</a> &amp; <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fftshift.html" rel="nofollow noreferrer">Scipy</a> implementations. Summary of my understanding:</p>\n<ul>\n<li>The natural order of <code>fft</code>'s return values, does not match a linear space of frequencies from <code>-dt</code> to <code>dt</code>.</li>\n<li>Hence, to get a frequency array that matches an array of frequency terms (from the output of <code>fft</code>), you either need to <code>fftshift</code> a <code>linspace</code> from <code>-1/dt</code> to <code>+1/dt</code>, or you'd need to <code>fftshift</code> the output of <code>fft</code>.</li>\n</ul>\n<p>I am wondering though: Why isn't the <code>fft</code> function implemented in <a href="https://www.mathworks.com/help/matlab/ref/fft.html" rel="nofollow noreferrer">Matlab</a>, <a href="https://numpy.org/doc/stable/reference/routines.fft.html" rel="nofollow noreferrer">Numpy</a> and <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fft.html" rel="nofollow noreferrer">Scipy</a> don't simply shift the output of it such that we'd get values that match linearly spaced frequencies from <code>-1/dt</code> to <code>+1/dt</code>? I'm sure there is a CPU/memory performance consideration here, but it'd be nice to get a thorough explanation for that.</p>\n<p>Even if the CPU/memory performance consideration will be justified, it'd be nice to hear about examples of calculations that won't require you to <code>fftshift</code> a linearly spaced frequencies from <code>-1/dt</code> to <code>+1/dt</code> (or use Numpy's <code>fftfreq</code>), and therefor that would be more performant thanks to the <code>fft</code> returning an array in it's current, natural order.</p>\n<p>One example I could think about for the above performance gain is convolution, which can be implemented as element-wise multiplication of <code>fft</code> outputs, (which therefor don't care about the order of the values, as long as it is consistent of course).</p>\n<p>Perhaps there are other reasons not to <code>fftshift</code> by default the output of <code>fft</code>, which are worth mentioning.</p>\n"^^ . . "In MATLAb you can give `dbstop if warning` to have execution pause in the debugger at the point that a warning is issued. In the debugger you have access to the full call stack, as well as all the variables that exist at each level of the call stack."^^ . . . . . . . ".net"^^ . "0"^^ . . . . "0"^^ . . "<p>I'm using Matlab notation. I have a matrix A of size (Nx3) where each entry of A is a positive integer. I want to create a matrix Q of dimensions (max(max(A))x2). Row i of Q corresponds to the column indices of A so that A(k,r) = i. So, if A(k_1,r_1) = i and A(k_2,r_2) = i, we can set Q(i,:)=[k_1,k_2]. For the unique entries of A, the associated row of Q has each column equal.</p>\n<p>Is there a way to vectorize the task? I can perform the task using loops, but it is very inefficient in MATLAB (when matrix A has large rows and max(max(A)) is also big). Here is an example.</p>\n<pre><code>A=[ 1 10 9\n 1 2 4\n 3 2 11\n 3 12 5\n 6 13 4\n 6 7 15\n 8 7 5\n 8 14 16]\n</code></pre>\n<p>In the above example, the expected result would be</p>\n<pre><code>Q =\n 1 1\n 2 2\n 1 1\n 3 3\n 3 3\n 1 1\n 2 2\n 1 1\n 3 3\n 2 2\n 3 3\n 2 2\n 2 2\n 2 2\n 3 3\n 3 3\n</code></pre>\n<p>This is what my slow code does</p>\n<pre><code>max_Q = max(max(A));\nQ = zeros(max_Q,2);\nfor i = 1 : max_Q\n [~,cols] = find(i == A); \n Q(i,:) = cols;\nend\n</code></pre>\n"^^ . "Is there a programmatic way to generate s-functions directly out of Simulink blocks"^^ . "<p><strong>The workflow can be summarized as follows</strong>:</p>\n<p><strong>Code generation settings</strong>:</p>\n<ul>\n<li>Change the system target file to 'rtwsfcn.tlc'.</li>\n<li>In Code generation settings enable 'create new model'</li>\n<li>In Code generation settings uncheck 'Generate code only'.</li>\n</ul>\n<p><strong>Once the above steps are done go ahead with building the model block programmatically:</strong></p>\n<pre><code>oldBlockPath=getfullname(gcbh);\nnewBlockHandle=slbuild(gcbh) % gcbh points to handle of current selected block \nnewBlockPath=getfullname(newBlockHandle);\npil_block_replace(oldBlockPath,newBlockPath);\n</code></pre>\n<p>The above code snippet can implement the idea at a fundamental level for a selected block.</p>\n<p>Reference: <a href="https://How%20to%20generate%20a%20Simulink%20S-Function%20programmatically?%20-%20MATLAB%20Answers%20-%20MATLAB%20Central" rel="nofollow noreferrer">MATLAB Answer's</a></p>\n"^^ . "0"^^ . . . "2"^^ . "statistics"^^ . . "Please supply a reproducible example. These functions are called from a script. That script would be helpful."^^ . . . "Please extract the part that that does the optimization, the part that you replace with a MATLAB function and found to be wrong. And then only post that part, with a small driver script that sets the input values. The rest is irrelevant to your question, and just makes it harder for us to help you. See [mre]."^^ . "<p>I am trying to run a psychophysics experiment in MATLAB, where timings of stimuli are very crucial. I have code to generate a sequence of ones, twos, and threes, each of which will trigger different stimuli to be displayed. When stimulus 2 is displayed, the participant has 1s to respond via a button press (using a ResponsePixx button box).</p>\n<p>I need each stimulus to be delivered 0.5s after the previous, which means that the response time to stimulus 2 overlaps with the delivery of the following stimulus. So I think I need to somehow track for the button press in the background whilst continuing to deliver the stimuli sequence.</p>\n<p>Here's the simplified version that just reduces it down to this current problem:</p>\n<pre><code>% Create sequence of numbers\nsequence = %FUNCTION OUTPUTS 1XN SEQUENCE OF ONES, TWOS, AND THREES\n\nfor iSequence = 1:length(sequence)\n \n disp(sequence(iSequence)) % Stand-in for displaying proper stimuli\n \n if sequence(iSequence) == 2\n % wait for 1 second whilst continuing display of sequence)\n % During this time, other code will run to track for participant responses\n disp(&quot;Time elapsed&quot;) \n end\n \n pause (0.5)\n \nend\n\n</code></pre>\n<p>I have done some testing with parfeval with no success - the output is displayed correctly, but interrupts the timing of the main sequence delivery (I assume as a delay to fetching the outputs from the parallel pool, but to be honest I have very little experience with parallel processing so I'm not sure):</p>\n<pre><code>delete(gcp('nocreate'))\nclear \n\nbackground = parpool(1);\n\nsequence = % createTrialSequence\n\n\n\nfor iSequence = 1:length(sequence)\n disp(sequence(iSequence))\n \n if iSequence &gt; 1\n if sequence(iSequence - 1) == 2\n fetchOutputs(evalButton)\n end\n end\n \n if sequence(iSequence) == 2\n evalButton = parfeval(background, @trackInBackground, 1);\n end\n \n pause(0.5)\n \nend\n</code></pre>\n<p>I have also tried using an event and listener, but this also pauses the delivery of the sequence (again, not hugely familiar with how these work, so may be missing something crucial):</p>\n<pre><code>clear\nevent = targetAppeared;\nlistener = trackTargetAppearance(event);\n\nsequence = %createTrialSequence\n\n\n\nfor iSequence = 1:length(sequence)\n disp(sequence(iSequence))\n \n \n if sequence(iSequence) == 2\n event.isTarget\n end\n \n pause(0.5)\n \nend\n\n\nclassdef targetAppeared &lt; handle\n events\n targetEvent\n end\n methods\n function isTarget(obj)\n notify(obj, 'targetEvent')\n \n end\n end\nend\n\nclassdef trackTargetAppearance &lt; handle\n\n methods\n function obj = trackTargetAppearance(targetObj)\n addlistener(targetObj, 'targetEvent', @trackTargetAppearance.handleEvent)\n end\n end\n \n methods (Static)\n function handleEvent(~, ~)\n startTime = GetSecs; %get system time, from PsychToolBox\n while GetSecs &lt; (startTime + 1)\n continue\n end\n disp(&quot;Target Response Window elapsed&quot;)\n end\n end \nend\n</code></pre>\n"^^ . "0"^^ . . . "2"^^ . "0"^^ . "0"^^ . . . . . . . "<p>I am working on a Bluetooth LE mesh network project with various devices distributed in an urban environment. <strong>My goal is to determine the minimum node density per square kilometer required for the network to function effectively.</strong></p>\n<p>To explore this, I am using MATLAB, specifically the Bluetooth Toolbox library, to simulate a Bluetooth mesh network within a 200x200 meter area. In the simulation:</p>\n<ul>\n<li>N nodes are randomly generated alongside a few buildings (represented as gray blocks).</li>\n<li>A transmitter and receiver are selected.</li>\n<li>The mesh network is initialized, and packets are exchanged over a 10-second period.</li>\n</ul>\n<p>The script identifies active links between nodes based on the remaining power, which is calculated as the difference between the transmission power and the path loss. If the remaining power exceeds -70 dBm (the detection threshold for most receivers), the link is considered active. These active links are displayed on a figure using color grading.</p>\n<p>However, i am encountering two major issues:</p>\n<ol>\n<li>I am struggling to correctly implement attenuation for BLE propagation using Free-Space Path Loss.</li>\n<li>Even when active links are present, the simulation often returns zero values for key metrics like Latency, Packet Loss Ratio (PLR), and Packet Delivery Ratio (PDR), which is not the expected outcome.</li>\n</ol>\n<p>CODE:</p>\n<pre><code>% Initialize the wireless network simulator\nnetworkSimulator = wirelessNetworkSimulator.init;\n\n% Parameter to enable or disable the maximum distance constraint\nmaintainDistanceConstraint = true; % Set to false to disable the maximum distance constraint\n\n% Define the area and node parameters\nareaSide = 200;\nnumNodes = 12; % Total number of nodes\nminReceivedPower = -70; % Minimum received power threshold in dBm\nmaxDistance = 70; % Maximum distance between nodes (valid only if maintainDistanceConstraint is true)\nmaxLinkDistance = 100; % Maximum distance to consider a link active\ntransmissionPower = 20; % Transmitted power in dBm\n\n% Operating frequency of the Bluetooth LE signal (2.4 GHz)\nfrequency = 2.4e9;\n\n% Function to calculate free space path loss\ncalculateFreeSpacePathLoss = @(distance, frequency) ...\n 20 * log10(distance) + 20 * log10(frequency) - 147.55; % Result in dB\n\n% Initialize the position matrix\nnodePositions = zeros(numNodes, 3); % Including z = 0\n\n% Random generation of rectangular obstacles (buildings) without overlap\nnumBuildings = 5; % Number of buildings\nbuildings = struct('x', [], 'y', [], 'width', [], 'height', []);\nfor i = 1:numBuildings\n validBuilding = false;\n maxAttempts = 1000;\n attempts = 0;\n\n while ~validBuilding &amp;&amp; attempts &lt; maxAttempts\n attempts = attempts + 1;\n\n % Random dimensions for the building (between 20x20 and 80x80 meters)\n width = 20 + rand * 60;\n height = 20 + rand * 60;\n\n % Random position for the building\n x = rand * (areaSide - width);\n y = rand * (areaSide - height);\n\n % Check for overlap with existing buildings\n overlap = false;\n for j = 1:i-1\n if ~(x + width &lt; buildings(j).x || buildings(j).x + buildings(j).width &lt; x || ...\n y + height &lt; buildings(j).y || buildings(j).y + buildings(j).height &lt; y)\n overlap = true;\n break;\n end\n end\n\n if ~overlap\n validBuilding = true;\n buildings(i).x = x;\n buildings(i).y = y;\n buildings(i).width = width;\n buildings(i).height = height;\n end\n end\n\n if ~validBuilding\n warning(&quot;Could not place building %d without overlaps after %d attempts.&quot;, i, maxAttempts);\n end\nend\n\n% Node generation with or without maximum distance constraint\nfor i = 1:numNodes\n validPosition = false;\n nodeAttempts = 0;\n maxNodeAttempts = 1000;\n\n while ~validPosition &amp;&amp; nodeAttempts &lt; maxNodeAttempts\n nodeAttempts = nodeAttempts + 1;\n newPosition = rand(1, 2) * areaSide;\n\n if maintainDistanceConstraint &amp;&amp; i &gt; 1\n distances = sqrt(sum((nodePositions(1:i-1, 1:2) - newPosition).^2, 2));\n distanceSatisfied = any(distances &lt;= maxDistance);\n else\n distanceSatisfied = true;\n end\n\n insideBuilding = false;\n for j = 1:numBuildings\n building = buildings(j);\n if newPosition(1) &gt; building.x &amp;&amp; newPosition(1) &lt; (building.x + building.width) &amp;&amp; ...\n newPosition(2) &gt; building.y &amp;&amp; newPosition(2) &lt; (building.y + building.height)\n insideBuilding = true;\n break;\n end\n end\n\n if distanceSatisfied &amp;&amp; ~insideBuilding\n validPosition = true;\n nodePositions(i, 1:2) = newPosition;\n end\n end\n\n if ~validPosition\n warning(&quot;Could not position node %d respecting constraints after %d attempts.&quot;, i, maxNodeAttempts);\n end\nend\n\n% Randomly select the transmitter and receiver\nrandomIndices = randperm(numNodes, 2);\ntransmitterIndex = randomIndices(1);\nreceiverIndex = randomIndices(2);\n\n% Create the transmitter node\nsourceNode = bluetoothLENode(&quot;broadcaster-observer&quot;, ...\n Name=&quot;Source Node&quot;, ...\n Position=nodePositions(transmitterIndex, :), ...\n TransmitterPower=transmissionPower); % Set transmission power\n\n% Create the receiver node\ndestinationNode = bluetoothLENode(&quot;broadcaster-observer&quot;, ...\n Name=&quot;Destination Node&quot;, ...\n Position=nodePositions(receiverIndex, :), ...\n TransmitterPower=transmissionPower); % Set transmission power\n\n% Configure Mesh profile for the transmitter node\ncfgMeshSource = bluetoothMeshProfileConfig(ElementAddress=&quot;0001&quot;);\nsourceNode.MeshConfig = cfgMeshSource;\n\n% Configure Mesh profile for the receiver node\ncfgMeshDestination = bluetoothMeshProfileConfig(ElementAddress=&quot;0002&quot;);\ndestinationNode.MeshConfig = cfgMeshDestination;\n\n% Create relay nodes\nrelayNodes = cell(1, numNodes - 2); % Initialize the relay nodes array\nrelayCounter = 1;\nfor i = 1:numNodes\n if i ~= transmitterIndex &amp;&amp; i ~= receiverIndex\n relayNode = bluetoothLENode(&quot;broadcaster-observer&quot;, ...\n Name=sprintf(&quot;Relay Node %d&quot;, relayCounter), ...\n Position=nodePositions(i, :), ...\n TransmitterPower=transmissionPower); % Set transmission power\n relayNodes{relayCounter} = relayNode; % Add relay node\n relayCounter = relayCounter + 1;\n end\nend\n\n% Create network traffic\ntraffic = networkTrafficOnOff(OnTime=inf, DataRate=1, PacketSize=15, GeneratePacket=true);\naddTrafficSource(sourceNode, traffic, SourceAddress=&quot;0001&quot;, DestinationAddress=&quot;0002&quot;, TTL=10);\n\n% Create the `nodes` array\nnodes = [{sourceNode}, relayNodes, {destinationNode}];\naddNodes(networkSimulator, [nodes{:}]);\n\n% Calculate active links and received power\nlinkMatrix = zeros(numNodes); % Adjacency matrix\nlinkPower = zeros(numNodes, numNodes); % Residual power for links\nminResidualPower = inf; % Minimum power value\nmaxResidualPower = -inf; % Maximum power value\n\nfprintf(&quot;\\nActive links in the mesh network:\\n&quot;); \n\nfor i = 1:numNodes\n %{\n - Check the distance between nodes.\n - Check for obstacles (buildings) on the link.\n - Calculate received power considering path loss.\n - Register the link as active if the received power exceeds the threshold.\n - Update the minimum and maximum residual power values.\n - Print active link information.\n %}\n for j = 1:numNodes\n if i ~= j\n distance = pdist2(nodePositions(i, :), nodePositions(j, :));\n if distance &lt;= maxLinkDistance\n % Check if a building is between the nodes\n buildingAttenuation = false;\n midX = (nodePositions(i, 1) + nodePositions(j, 1)) / 2;\n midY = (nodePositions(i, 2) + nodePositions(j, 2)) / 2;\n\n for k = 1:numBuildings\n building = buildings(k);\n if midX &gt; building.x &amp;&amp; midX &lt; (building.x + building.width) &amp;&amp; ...\n midY &gt; building.y &amp;&amp; midY &lt; (building.y + building.height)\n buildingAttenuation = true;\n break;\n end\n end\n\n if ~buildingAttenuation\n % Calculate path loss\n pathLoss = calculateFreeSpacePathLoss(distance, frequency);\n receivedPower = transmissionPower - pathLoss;\n\n if receivedPower &gt;= minReceivedPower\n linkMatrix(i, j) = 1; % Active link\n linkPower(i, j) = receivedPower;\n minResidualPower = min(minResidualPower, receivedPower);\n maxResidualPower = max(maxResidualPower, receivedPower);\n fprintf(&quot;Node %d -&gt; Node %d: Distance = %.2f m, Received Power = %.2f dBm\\n&quot;, ...\n i, j, distance, receivedPower);\n end\n end\n end\n end\n end\nend\n% Run the simulation\nsimulationTime = 10;\nrun(networkSimulator, simulationTime);\n\n% Retrieve and display statistics\nsourceStats = statistics(sourceNode);\ndestinationStats = statistics(destinationNode);\nrelayStats = cellfun(@statistics, relayNodes, 'UniformOutput', false);\n\ndisp(&quot;Transmitter node statistics:&quot;);\ndisp(sourceStats);\ndisp(&quot;Receiver node statistics:&quot;);\ndisp(destinationStats);\n\n% Calculate and display KPIs\nlatency = kpi(sourceNode, destinationNode, &quot;latency&quot;, Layer=&quot;App&quot;);\nplr = kpi(sourceNode, destinationNode, &quot;PLR&quot;, Layer=&quot;App&quot;);\npdr = kpi(sourceNode, destinationNode, &quot;PDR&quot;, Layer=&quot;App&quot;);\n\nfprintf(&quot;\\nBluetooth Mesh Network KPIs:\\n&quot;);\nfprintf(&quot;Latency: %.2f ms\\n&quot;, latency * 1000); % Converted to milliseconds\nfprintf(&quot;Packet Loss Ratio (PLR): %.2f\\n&quot;, plr);\nfprintf(&quot;Packet Delivery Ratio (PDR): %.2f\\n&quot;, pdr);\n\n% Visualize the mesh network\nfigure;\nhold on;\n\n% Draw buildings\nfor i = 1:numBuildings\n rectangle('Position', [buildings(i).x, buildings(i).y, buildings(i).width, buildings(i).height], ...\n 'FaceColor', [0.5 0.5 0.5], 'EdgeColor', 'k');\nend\n\n% Draw nodes\nfor i = 1:numNodes\n if i == transmitterIndex\n scatter(nodePositions(i, 1), nodePositions(i, 2), 250, 'r', 'filled'); % Transmitter (red)\n elseif i == receiverIndex\n scatter(nodePositions(i, 1), nodePositions(i, 2), 250, 'g', 'filled'); % Receiver (green)\n else\n scatter(nodePositions(i, 1), nodePositions(i, 2), 200, 'b', 'filled'); % Other nodes (blue)\n end\nend\n\n% Draw links\nfor i = 1:numNodes\n for j = 1:numNodes\n if linkMatrix(i, j) == 1\n powerNorm = (linkPower(i, j) - minResidualPower) / ...\n (maxResidualPower - minResidualPower);\n linkColor = [1 - powerNorm, powerNorm, 0]; % Gradient from red to green\n plot([nodePositions(i, 1), nodePositions(j, 1)], ...\n [nodePositions(i, 2), nodePositions(j, 2)], '-', ...\n 'Color', linkColor, 'LineWidth', 2);\n end\n end\nend\n\ntitle('Distribution of Nodes, Buildings, and Active Links in the Bluetooth Mesh Network');\nxlabel('X Position (meters)');\nylabel('Y Position (meters)');\nxlim([0 areaSide]);\nylim([0 areaSide]);\ngrid on;\naxis equal;\nhold off;\n</code></pre>\n<p><a href="https://i.sstatic.net/WxpGHjcw.png" rel="nofollow noreferrer">enter image description here</a></p>\n<p>Currently, my approach is as follows:</p>\n<ul>\n<li>Set a transmission power of 20 dBm for each node.</li>\n<li>Use a free-space path loss function to calculate attenuation based on the distance between nodes.</li>\n<li>Determine active links if the remaining power exceeds -70 dBm and reflect these links in the linkMatrix and linkPower matrices.</li>\n</ul>\n<p>I am trying to adjust the simulation to only process data and compute metrics using the active links, but i am unsure how to implement this next step. I also know from the official MATLAB documentation that there is a way to account for attenuation directly using built-in library functions, but i am struggling to integrate this feature into the programming logic.</p>\n<p>What i expect is for the script to compute and return realistic, non-zero values for Latency, Packet Loss Ratio (PLR), and Packet Delivery Ratio (PDR) when the transmitter and receiver are actively linked.</p>\n"^^ . "That is exactly what I mean with "for visualization". If you're not looking at it, it doesn't matter whether it looks pretty or not."^^ . "0"^^ . . . . . . "<p>I have two matrices:</p>\n<pre><code>A = [ -1 0 0;\n 1 1 -1;\n 0 -1 1 ];\nB = [-1; 0; 1];\n</code></pre>\n<p>and I want to solve the following equation:</p>\n<pre><code>Ax=B\n</code></pre>\n<p>when I use <code>mldivide</code> function I get a matrix of NaNs</p>\n<pre><code>X = mldivide(A,B)\nX =\n\n NaN\n NaN\n NaN\n</code></pre>\n<p>Knowing there are multiple solutions to this problem I manually tested if one of them, namely <code>[1;0;1]</code> returns <code>B</code>:</p>\n<pre><code>A*[1; 0; 1]\n</code></pre>\n<p>and, as expected, I reassured myself that it is one of multiple solutions.\nSo here is my question:\nwhy does <code>mldivide</code> return incorret solution?</p>\n"^^ . . "0"^^ . "0"^^ . "1"^^ . . . "1"^^ . . "1"^^ . . . . "Why was `fftshift` invented for? Why not `fftshift` by default the output of the current `fft` implementations?"^^ . "0"^^ . "transfer-function"^^ . . . . . . . . . . . "mapping"^^ . . . . . "0"^^ . "0"^^ . "Thank you for the response, your solution #2 is more inline with what I'm trying to do, but when I use that solution, I get the error:\nError in initialize/init (line 39)\n app.buttons = buttons( app.gridLayout );\n ^^^^^^^^^^^^^^^^^^^^^^^^^\nError in initialize (line 52)\n init(app)\n ^^^^^^^^^"^^ . "1"^^ . "1"^^ . . "@CrisLuengo: I guess that answers one possible reading of the question, like "does MATLAB pin its threads to the P-cores to match its default thread count?" (i.e. is thread pinning part of the distinction it makes). And this is answering "no". That isn't what I thought it was asking, which as I commented under the question, I think it's asking how MATLAB figures out which cores are which so it can count the number of physical P cores in the first place. This answer doesn't answer that at all. OS thread APIs don't currently report E vs. P core counts; they predate such CPUs."^^ . . "0"^^ . . "if so, then please either post a self-answer or delete the question altogether"^^ . . . . . . "0"^^ . . . "Hi @jonsson this was helpful so thank you. What I found that worked well was instead of trying to write the commands in MATLAB and such having to convert the VBA into a compatible format for MATLAB, was rather to just write a VBA macro that created the TOC and made it hyperlinks and then call this macro in my MATLAB script. This way I can do the data processing I need to in MATLAB and then simply call the VBA commands that I couldn't convert, as macros. This solved my problem entirely."^^ . . "Setting a max runtime for an optimiser"^^ . "0"^^ . . . "The error message "error using norm first argument must be single or double" pretty clearly indicates that your array has to be `float` or `double` rather than `int`. Have you tried `double[,] input = new double[...] ...`?"^^ . . . . . "<p>You can get the common timestamps, then filter <code>A</code> and <code>B</code> for columns with timestamps in this array</p>\n<pre><code>t = intersect( A(1,:), B(1,:) ); % Get common timestamps\nA = A( :, ismember(A(1,:), t) ); % Only retain cols with timestamps in common array\nB = B( :, ismember(B(1,:), t) ); % Only retain cols with timestamps in common array\n</code></pre>\n<hr />\n<p>Alternatively, you could just remove columns from A where the timestamp isn't in B, and then vice versa:</p>\n<pre><code>A( :, ~ismember(A(1,:),B(1,:)) ) = []; % Remove A cols not in B's timestamps\nB( :, ~ismember(B(1,:),A(1,:)) ) = []; % Remove B cols not in A's timestamps\n</code></pre>\n"^^ . . "I noticed an issue: if the size of the training set images differs significantly from the test set images, reducing the test images to match the training size may cause feature loss. Will this have a significant impact?"^^ . . "0"^^ . "dbstop"^^ . . . . "parameters"^^ . . . "convolution"^^ . "0"^^ . . "image-processing"^^ . . "Agreed. If only Mathworks had given us run-length encoding and cumulative run-length."^^ . . . . . . . "Yea, all of the integers [1:max(max(A))] guaranteed to appear. That is correct, setting Q(i,:)=[k_1,k_1] when there is only one instance of i."^^ . . "0"^^ . . . . . "Why do I get a "Unable to find connector client." error when using restFunctionService"^^ . "Restart simulation when slider gain value is adjusted"^^ . . . . . . . "0"^^ . . "2"^^ . "0"^^ . . "-1"^^ . . "Thank you . Figured it to be the issue ."^^ . "cpu-cores"^^ . . . . . . "0"^^ . . "0"^^ . . . . "And will there ever be a case where `k_1 != k_2`? It doesn't appear so from your example."^^ . . . "Compressed sensing with FFT basis"^^ . . "0"^^ . . "1"^^ . . "2"^^ . . . . "0"^^ . "stl-format"^^ . . . . . "Direct Sequence Spread Spectrum (DSSS) of Binary Phase Shift Keying (BPSK)"^^ . . . "1"^^ . . . "0"^^ . "<p>This is a potential solution using a <a href="https://mathworks.com/help/matlab/ref/timer.html" rel="nofollow noreferrer"><code>timer</code></a></p>\n<p>Excuse the clutter of code due to building a minimal GUI for this, the only mechanisms to focus on are:</p>\n<ul>\n<li><p>Use a <a href="https://mathworks.com/help/matlab/ref/timer.html" rel="nofollow noreferrer"><code>timer</code></a> to trigger the stimuli display/change at regular interval (in particular, look at the <code>ExecutionMode</code>option of the timer, which lets you adjust how regular the timer firing is)</p>\n</li>\n<li><p>When the stimuli necessitating a (timed) response from the user is displayed, start a <a href="https://uk.mathworks.com/help/matlab/ref/tic.html" rel="nofollow noreferrer"><code>stopwatch</code></a></p>\n</li>\n<li><p>When the user button press is detected, read the value of the stopwatch and act in consequence.</p>\n</li>\n</ul>\n<hr />\n<p><a href="https://i.sstatic.net/51X32ikH.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/51X32ikH.gif" alt="Timed response" /></a></p>\n<hr />\n<p>The code for the example above:</p>\n<pre><code>function hf = TimedResponse\nglobal sequence ;\n\n sequence = 1:10 ;\n hf = build_gui ;\n \nend\n\nfunction myTimerFcn(~,~,hfig)\nglobal sequence ;\nglobal responseTimer ;\npersistent iseq ;\n\n hf = guidata(hfig) ;\n if isempty(iseq) ; iseq=1 ; end\n if iseq&gt;numel(sequence) ; iseq=1 ; end\n \n hf.lbl.String = num2str(sequence(iseq)) ;\n \n if sequence(iseq) == 2\n responseTimer = tic ;\n end\n iseq = iseq+1 ;\nend\n\nfunction StartButtonPushed(src,~)\n hf = guidata(src) ;\n if strcmpi(hf.t.Running,'off')\n start(hf.t) ;\n hf.btnStart.String = 'Stop';\n else\n stop(hf.t) ;\n hf.btnStart.String = 'Start';\n end\nend\n\nfunction RespButtonPushed(src,~)\nglobal responseTimer ;\n\n hf = guidata(src) ;\n ElapsedTime = toc(responseTimer) ;\n if ElapsedTime &lt; 1\n hf.lblresp.ForegroundColor = 'g' ;\n hf.lblresp.String = sprintf('*** PASS *** (Time to respond to stimuli: %f seconds)',ElapsedTime) ;\n else\n hf.lblresp.ForegroundColor = 'r' ;\n hf.lblresp.String = sprintf('*** TOO LATE *** (Time to respond to stimuli: %f seconds)',ElapsedTime) ;\n end\n \nend\n\nfunction h = build_gui\n\n h.fig = figure('unit','normalized','CloseRequestFcn',@my_closereq);\n h.t = timer('Period',0.5,'ExecutionMode','fixedDelay') ;\n h.t.TimerFcn = @(e,v)myTimerFcn(e,v,h.fig) ;\n \n h.btnStart = uicontrol('Style','pushbutton','String','Start','unit','normalized','Position',[0.1 0.8 0.8 0.1],'Callback',@StartButtonPushed);\n h.lbl = uicontrol('Style','text','String','0','unit','normalized','Position',[0.1 0.4 0.8 0.3],'FontSize',36);\n h.btnResp = uicontrol('Style','pushbutton','String','Stimuli observed','unit','normalized','Position',[0.1 0.2 0.8 0.1],'Callback',@RespButtonPushed);\n h.lblresp = uicontrol('Style','text','String','','unit','normalized','Position',[0.1 0.1 0.8 0.05],'FontSize',12);\n\n h.seq = 1:10 ;\n guidata(h.fig,h)\nend\n\nfunction my_closereq(src,~)\n hf = guidata(src) ;\n disp('Deleting timer') ;\n if strcmpi(hf.t.Running,'on')\n stop(hf.t) ;\n end\n delete(hf.t) ;\n delete(hf.fig) ;\nend\n</code></pre>\n"^^ . . . . "0"^^ . . . . . "0"^^ . "<p>I managed pass an identifier to the <code>MATLAB Function</code> blocks allowing me to trace the origin of prints or warnings afterwards, by following these steps :</p>\n<ol>\n<li>Create a mask parameter on top of the <code>MATLAB Function</code>.</li>\n<li>Pass the parameter as input to the <code>MATLAB function</code> in the function definition. This step requires specifying the entry as a <code>Parameter Data</code> within the Modeling/Symbols Pane panel.</li>\n<li>Run a script that set up the identifier for each of the <code>MATLAB Function</code> blocks.</li>\n<li>When the model runs, and displays warnings it prints the identifier as well as the warning for debugging purposes.</li>\n</ol>\n<p>Note : I did not manage to pass the path to the block (<code>model_name/subsystem/subsytem2/etc...</code>) as a string as intended, but instead relied on the fact that I have a numerical identifier for each block of the model, which is specific to my application.</p>\n<p><em>I believe this can be improved, maybe with a more generic answer, but this has solved my issue in my application for now.</em></p>\n"^^ . . . "loglog"^^ . "Are you asking how it classifies a core as P or E after checking its `cpuid` results or something? On current systems, the max MHz for E cores is lower than P cores, so that's one common way to check. The model/family info may be the set to report the same because some anti-piracy software assumed real systems were homogeneous, so it's not as easy as just looking at model/family. Related: [How to detect P/E-Core in Intel Alder Lake CPU?](https://stackoverflow.com/q/69955410) / [How to detect E-cores and P-cores in Linux alder lake system?](https://stackoverflow.com/q/71122837)"^^ . . . "<p>I have a question to the command <code>fft</code> in Matlab. By using the default settings Matlab assumes the signal to be periodic with a periodicity of 2π. However, for my problem I need to apply the FFT to a signal that is periodic in L ≠ 2π.</p>\n<p>I am sure there is a proper function for this in Matlab. I am pretty new in Matlab and I didn't find anything in the documentation of <code>fft</code>.</p>\n<p>To be precise: I want fast fourier transform an array with N emenets by using the frequencies [0, L/N,..., L*(N-1)/N]. I know that it would be easy to write a code by simply calculating the fft manually, but I guess there must be an efficient command available in matlab.</p>\n"^^ . "2"^^ . "0"^^ . . . . . "0"^^ . . "0"^^ . . "<p>In Matlab, I am doing a curve fitting of a set of points, which follow a power law. If I use the <code>'log(a*x^n)'</code> power law as the main argument of the <a href="https://ch.mathworks.com/help/curvefit/fittype.html" rel="nofollow noreferrer">fittype</a> function, everything works well:</p>\n<pre><code>% input\nx = [4 9 15 25 35 45 55 65 75 85 95 150 250 350 450 900];\ny = [335 28 37 9 4 3.5 2 1 0.7 0.6 0.5 0.3 0.1 0.01 0.005 0.001];\n% curve fitting\nft = fittype('log(a*x^n)','independent','x');\n[fitresult, gof] = fit(x',log(y)',ft,'Startpoint', [1 -1]);\n% plots\nhold on\nplot(x,y,'o-','Color','b')\nplot(x,(fitresult.a .* (x.^fitresult.n)),'-','color','r')\nset(gca, 'XScale', 'log', 'YScale', 'log');\n</code></pre>\n<p><a href="https://i.sstatic.net/2fkbwnBMl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2fkbwnBMl.png" alt="enter image description here" /></a></p>\n<p>However, if I add an additional parameter, <code>b</code> (i.e. the y-intercept), to the previous power law, i.e. now being <code>'log(a*x^n + b)'</code>, in the <a href="https://ch.mathworks.com/help/curvefit/fittype.html" rel="nofollow noreferrer">fittype</a> function...</p>\n<pre><code>% input\nx = [4 9 15 25 35 45 55 65 75 85 95 150 250 350 450 900];\ny = [335 28 37 9 4 3.5 2 1 0.7 0.6 0.5 0.3 0.1 0.01 0.005 0.001];\n% curve fitting\nft = fittype('log(a*x^n + b)','independent','x');\n[fitresult, gof] = fit(x',log(y)',ft,'Startpoint', [1 -1 1]);\n% plots\nhold on\nplot(x,y,'o-')\nplot(x,(fitresult.a .* (x.^fitresult.n)),'-')\nset(gca, 'XScale', 'log', 'YScale', 'log');\n</code></pre>\n<p>I get the following error:</p>\n<pre><code>Error using fit&gt;iFit\nComplex value computed by model function, fitting cannot continue.\nTry using or tightening upper and lower bounds on coefficients.\n\nError in fit (line 117)\n[fitobj, goodness, output, convmsg] = iFit( xdatain, ydatain, fittypeobj, ...\n\nError in untitled6 (line 6)\n[fitresult, gof] = fit(x',log(y)',ft,'Startpoint', [1 -1 1]);\n</code></pre>\n<p><strong>How can I solve this error and - in general - make the <a href="https://ch.mathworks.com/help/curvefit/fittype.html" rel="nofollow noreferrer">fittype</a> function work for a logged power law which includes a y-intercept?</strong></p>\n"^^ . "p-value"^^ . . . . . . . . . . . . . "0"^^ . . . . "1"^^ . "<p>The issue I thought I had with generating a <code>uuid</code> from my octave script was a red herring. Within the the function I was calling, I'm doing <code>extract(epoch from tts.timestampt)</code>; it was the <code>numeric</code> value returned by postgres that was actually giving <code>octave</code> trouble. Changing that data type allowed my function to execute as expected with a <code>uuid</code> parameter.</p>\n"^^ . "0"^^ . . . . . . "connected-components"^^ . . "2"^^ . . . . "1"^^ . . "0"^^ . . . . "0"^^ . "simulink-library"^^ . "Alternatively, change the assignment in your loop to `fourdmatrix(:,:,:,i) = cell{i};`"^^ . "I discovered that it has to do with both numerical precision and permutation. In Julia, I computed: `R = sparse(cholesky(K).L)'` without permuting it to better condition the matrix, and to my surprise, I got exactly the same result as in MATLAB, with a difference in the 18th decimal place."^^ . "simulink"^^ . . "To add on Ander's coment, the MATLAB fft2 is already using multithreading and is quite fast."^^ . . . . . . . . "0"^^ . "0"^^ . . . . . . "0"^^ . "scipy"^^ . "0"^^ . . "If graph coloring is, in fact, what you're looking for, 4-coloring a planar graph isn't hard, so it would definitely be feasible to write your own. We just need clarification on your expected output."^^ . "0"^^ . . . "0"^^ . . . "Sorry about that, heres the full error, >> initialize\nError using uibutton (line 55)\n'Parent' must be a parent component, such as a uifigure object.\n\nError in buttons (line 9)\n obj.fileload1 = uibutton(grid, 'push');\n ^^^^^^^^^^^^^^^^^^^^^^\nError in initialize/init (line 39)\n app.buttons = buttons( app.gridLayout );\n ^^^^^^^^^^^^^^^^^^^^^^^^^\nError in initialize (line 52)\n init(app)\n ^^^^^^^^^"^^ . "Regarding SOS, no it is not just the same array, the function `butter` has a input parameter called `output` which can be set to `sos`."^^ . "<p>Your vector <code>n</code> is not smooth, and doesn't represent a parallel gradient to any vector direction. You can see this by just using <code>plot(n)</code>, it aligns with the representation you get. This code shows how you can plot a gradient perpendicular to a given vector:</p>\n<p>You can use <code>atan2</code> to work out the direction of your vector <code>aUV</code>, and set the colour equal to <code>cos(theta + aUV + pi/2)</code>, since you want to start drawing the colours offset by <code>aUV</code> from where you're drawing the circular <code>patch</code> and the additional <code>pi/2</code> makes the gradient perpendicular.</p>\n<pre><code>% Some setup values\nN = 32; % Number of samples in array\nU = -4.6492; % X displacement of vector\nV = -0.9099; % Y displacement of vector\n% Calculate circle drawing vectors\naUV = atan2(U,V); % Angle of UV vector\ntheta = linspace(0,2*pi,N); % Angle array for drawing patch\nclr = cos(theta + aUV + pi/2); % Offset cyclic colour starting from aUV+pi/2\n% Plot\nfigure(1); clf; hold on;\npatch(cos(theta), sin(theta), clr, 'EdgeColor', 'none');\nquiver(0,0,U,V,0.5,'k','linewidth',3);\naxis equal; colormap spring\n</code></pre>\n<p>Output:</p>\n<p><a href="https://i.sstatic.net/fzOCWpz6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fzOCWpz6.png" alt="output plot" /></a></p>\n<hr />\n<p>Edit with respect to question update...\n<strong>If you do not have the angle or direction vector as an input</strong> we can determine it from the input <code>n</code> by</p>\n<ul>\n<li>Upsampling with piecewise cubic interpolation</li>\n<li>Finding the peak</li>\n<li>Plotting in a similar way to above</li>\n</ul>\n<p>See the code comments for details</p>\n<pre><code>% Sort theta so that we can interpolate with it as the axis\n[theta,idx] = sort(theta);\nn = n(idx); % Match the order of points in 'n' with sorted theta\n% Upsample 'n' using piecewise cubic interpolation\ntheta_i = linspace(theta(1),theta(end),1000);\nn_i = interp1( theta, n, theta_i, 'pchip' );\n% Find the index for the max value of 'n'\n[n_max,idx] = max(n_i);\naUV = theta_i(idx);\n\n% Offset cyclic colour starting from aUV\nclr = cos(theta - aUV); \n\n% Plotting... side by side of input curve with gradient for comparison\nlabel = sprintf('\\\\theta=%.3f',aUV); % helper for legend labelling\nfigure(1); clf; \n\nsubplot(1,3,1); hold on;\nplot(theta,n,'displayname','Input &quot;n&quot;');\nplot(theta_i,n_i,'displayname','Upsampled &quot;n&quot;');\nplot(aUV,n_max,'kx','displayname',['Peak &quot;n&quot; at ' label]);\nlegend('show','location','south');\n\nsubplot(1,3,2:3); hold on;\npatch(cos(theta), sin(theta), clr, 'EdgeColor', 'none','displayname','gradient');\nline( [-1,1]*cos(aUV), [-1,1]*sin(aUV), 'color', 'k', 'displayname', ['Ref line at ' label]);\naxis equal; colormap parula; legend show\n</code></pre>\n<p>Result:</p>\n<p><a href="https://i.sstatic.net/rE5rpKsk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rE5rpKsk.png" alt="updated plot" /></a></p>\n"^^ . . . . "2"^^ . . . . . . "<p>The MSDN VBA documentation is usually a good reference for how to programmatically control Excel from MATLAB, since the syntax with the COM interface for Excel is closely aligned with VBA.</p>\n<p>In particular, from the GoalSeek VBA docs:</p>\n<p><a href="https://learn.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa195749(v=office.11)" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa195749(v=office.11)</a></p>\n<p>The <strong>VBA</strong> code would be something like:</p>\n<pre><code>Worksheets(&quot;Sheet1&quot;).Range(&quot;C3&quot;).GoalSeek _\n Goal:=15, _\n ChangingCell:=Worksheets(&quot;Sheet1&quot;).Range(&quot;B3&quot;)\n</code></pre>\n<p>We can do this in <strong>MATLAB</strong> as follows:</p>\n<pre><code>workbookName = 'Test.xlsx';\nsheetName = 'Sheet1';\ngoalseekAddr = 'C3';\ngoalseekVal = 15;\nchangeAddr = 'B3';\n\nsheet = getSheet( workbookName, sheetName );\nchangeCell = sheet.Range(changeAddr);\ninvoke( sheet.Range(goalseekAddr), 'GoalSeek', goalseekVal, changeCell );\n</code></pre>\n<p>You have to use <code>invoke</code> to call the GoalSeek function, but otherwise it's operating on the same inputs</p>\n<ul>\n<li>It's a function of the range you wish to seek on</li>\n<li>The first input argument is the value to seek for</li>\n<li>The second input is the cell to change</li>\n</ul>\n<p><code>getSheet</code> is a helper function I've written, but you might already have something which gets the <code>sheet</code> COM object via <code>actxserver</code></p>\n<hr />\n<p><em>Helper function</em></p>\n<pre><code>function sheet = getSheet( workbookName, sheetName )\n % Try and connect to open Excel instance, open a new one if not\n try\n Excel = actxGetRunningServer('Excel.Application');\n catch\n Excel = actxserver('Excel.Application');\n end\n % Find the workbook by name\n workbook = [];\n for iwb = 1:Excel.Workbooks.Count\n if strcmpi( workbookName, Excel.Workbooks.Item(iwb).Name )\n workbook = Excel.Workbooks.Item(iwb);\n break;\n end\n end\n if isempty(workbook)\n Excel.Workbooks.Open( workbookName ); \n end\n % Assume the sheet exists...\n sheet = workbook.Sheets.Item(sheetName);\nend\n</code></pre>\n"^^ . . . . . . "0"^^ . "1"^^ . "0"^^ . . "<p>One you have the data in a 4d array it's simple enough, just use <code>mean</code> and supply the dimension to work over as you suggest. As @Cris notes you might run out of memory forming the 4d array (since it will copy all the data) in which case you'll want to loop over the existing arrays. But if you have enough memory this should work:</p>\n<pre><code>% make 12 random 3d arrays in cell array `c`\nfor i=1:12\n c{i} = rand(10, 10, 10); \nend\n\n% Make a 4d array:\narray4d = cat(4, c{:}); % Same as writing cat(4, c{1}, c{2}, c{3}, etc)\n\nm = mean(array4d, 4); % Take the mean along the 4th dimension\nsize(m) % Show the size of the output (here should be 10,10,10)\n</code></pre>\n"^^ . . . "0"^^ . "Why have you set MaxIter to 2000? do you really know if below 2000 it has all converged?"^^ . "Represent tiny numbers in Matlab using sym and vpa"^^ . "bluetooth-lowenergy"^^ . . "<p>I have a MATLAB code that is copying data to an Excel file and running hundreds of formulas (for anyone interested, I am using a revised version of CREST developed by NREL). Afterwards, I want to run a What-If Analysis using the goal seek ability in Excel to find the minimum cost of the product.</p>\n<p>Because of the complexity of the spreadsheet, I cannot recreate the formulas in MATLAB (in a timely fashion). The What-If Analysis works manually, but I would like to run goal seek for thousands of files. Is there a way to use MATLAB to execute this? I would like to open the spreadsheet, run the goal seek, save, and close the file and do this for thousands of files. I know how to do everything other than execute the goal seek.</p>\n<p>Thank you!</p>\n"^^ . . "1"^^ . . . . "0"^^ . "0"^^ . "<p>I am trying to create an FIR and associated waveform for a transfer function that is the magnitude difference between the two impulses responses. I have recorded both IR's but am struggling with getting the correction factor to be correct. Here is my code and results of the IRs and difference which is clearly wrong because it is reducing magnitude incorrectly. I can see kind of where it is going wrong which seems to be in taking the difference between them which results in the following magnitude graph and DBFS graph. I have included wav files as csv if trying to run.</p>\n<p>EDIT: updated code to show my target curve and the resulting correction curve. I have changed the code to divide instead of subtract as suggested which got me the result I desired. HOWEVER now when I look at the time-domain FIR of the correction curve it looks really wrong and funky. <a href="https://i.sstatic.net/H3G4EKFO.png" rel="nofollow noreferrer">time-domain plot of y result</a> here is the new code that should work.</p>\n<pre><code>% Define the sampling frequency\nclose all\n[x1,fs] = audioread('711_Tap1024.wav');\n[x2,fs] = audioread('5128_Tap1024.wav');\n\nNfft = length(x1);\n% Frequency vector (assume frequencies are normalized, or you need to normalize by fs/2)\nf = linspace(0, fs, Nfft);\nf = f';\n\n%define Target Curve\nx1FR = 20*log10(abs(fft(x1,Nfft)));\nx2FR = 20*log10(abs(fft(x2,Nfft)));\ntargetCurve = x1FR-x2FR;\ntargetCurve = targetCurve*-1;\n\n% Define or import the frequency responses H1 and H2\n% H1 = abs(fft(x1,Nfft));\n% H2 = abs(fft(x2,Nfft));\nH1 = fft(x1,Nfft);\nH2 = fft(x2,Nfft);\n\n% Compute the difference in frequency responses divide\n%H_diff = H1-H2;\nH_diff = H2./H1;\n\n% Inverse FFT to obtain the impulse response\ny = real(ifft(H_diff,Nfft));\n\n% Normalize the impulse response\ny = 0.99*y/max(abs(y));\n\n% Save the impulse response as a WAV file\naudiowrite('impulse_response_diff.wav', y, fs);\n\n% Plot the impulse response (optional)\nfigure;\nplot(y)\n\n% plot result of y\ny_new=abs(fft(y,Nfft));\ny_new= 20*log10(y_new);\n\nfigure\nplot(f(1:Nfft/2), x1FR(1:Nfft/2));\nhold on\nplot(f(1:Nfft/2), x2FR(1:Nfft/2));\nhold on\nplot(f(1:Nfft/2), targetCurve(1:Nfft/2));\nhold on\nplot(f(1:Nfft/2), y_new(1:Nfft/2));\n\nxlim([20 20000])\nxticks([100 1000 10000])\ngrid on\nset(gca, 'XScale', 'log')\nxlabel ('Frequency (Hz)');\nylabel ('Magnitude');\nlegend('H1', 'H2', 'Target Curve','Correction Curve')\n</code></pre>\n"^^ . . . "0"^^ . . . . . "1"^^ . "differential-equations"^^ . . "utm"^^ . "<p>There is a four-dimensional matrix data, along with corresponding X coordinates data_X and Y coordinates data_Y for each element. I want to perform a two-dimensional interval segmentation, or grid partitioning, based on edge_X and edge_Y, resulting in a new array data_class. The current loop implementation is very slow. How can I improve the computational speed?</p>\n<pre><code>clc;clear\nrng(&quot;default&quot;)\ndata = randi([0, 100], 40,30,20, 10);\ndata_X = randi([0, 100], 40,30,20, 10);\ndata_Y = randi([0, 100], 40,30,20, 10);\n\n% Define the edges for histograms in X and Y directions\nedge_X = [0:10:100];\nedge_Y = [0:20:100];\n\nsz = size(data);\nfor ix = 1:sz(1)\n for iy = 1:sz(2)\n for ii = 1:sz(3)\n for ij = 1:sz(4)\n % Extract the current data, X, and Y values\n g_data = data(ix, iy, ii, ij);\n g_X = data_X(ix, iy, ii, ij);\n g_Y = data_Y(ix, iy, ii, ij);\n \n % Compute the 2D histogram count \n g_id = histcounts2(g_X, g_Y, edge_X, edge_Y);\n g_new = g_id * g_data;\n data_class (ix,iy,ii,ij,:,:) = g_new; \n end\n end\n end\nend\n</code></pre>\n<p>Since each element of data is processed individually, g_data will only be noted as 1 in a bin, and then</p>\n<pre><code>g_new = g_id * g_data; \n</code></pre>\n<p>g_new is the position of g_data after reclassification</p>\n<p>The current loop implementation is very slow. How can I improve the computational speed?</p>\n"^^ . . . . . "0"^^ . "1"^^ . . "3"^^ . . "2"^^ . . . "What are “header file declarations”? Are you talking about include statements? Those are expected in a C file. Please clarify what you are seeing by including a [mre], and please explain why it is a problem. Also, don’t forget to ask a question explicitly. It makes it easier to provide an answer without guessing at what you want to learn."^^ . "0"^^ . . . . "<p>The behavior you're observing is actually expected - <code>runpf</code> performs a power flow calculation to determine if a solution exists that satisfies Kirchhoff's laws and the specified power injections/demands, but it does not enforce branch flow limits by default. This is because branch flow limits are typically considered as operational constraints rather than physical laws.</p>\n<p>If you need to find a solution that respects branch flow limits, I would recommend you to use MATPOWER's OPF functionality instead. The OPF will try to find a solution that satisfies power flow equations, respect branch flow limits, keep voltages within bounds, respect generator limits and minimize generation cost.</p>\n<p>You can read more about it here: <a href="https://matpower.org/docs/ref/matpower5.0/opf.html" rel="nofollow noreferrer">https://matpower.org/docs/ref/matpower5.0/opf.html</a></p>\n"^^ . . "0"^^ . "3"^^ . . "0"^^ . . . . "Just looking around *Windows* Word (without MatLab), when a TOC is generated by a field code, you generally need \\ \\h (backslash-h) in that code to make each entry in the TOC hyperlink. ActiveDocument.TablesOfCOntents(1).UseHyperlinks(1) = True does not appear to introduce a backslash-h, whereas if you do ActiveDocument.TablesOfContents.Add(rang,,,,,,,,,True) when you create the TOC, Word *does* insert the backslash-h. If I save that as .PDF I get hyperlinks to the headings..."^^ . . "1"^^ . . . "0"^^ . . "@CrisLuengo a good example where I'm sure you'd agree with me it is natural to view the frequency range from -N/2 to N/2 is the classical Gaussian Fourier transform that should produce a Gaussian as well - take a Gaussian with mean at 0, corresponding to values from `-x0` to `x0`; Run `fft` on it; Isn't it natural to expect a shifted sample of a Gaussian from `-1/dx` to `1/dx`?"^^ . "numpy"^^ . . . "Possible duplicates https://stackoverflow.com/a/18277039/3978545, https://stackoverflow.com/questions/58957369/unable-to-convert-matlab-timestamp-to-datetime-in-python,"^^ . . . "1"^^ . . . "FFT to compute a Bode diagram to find resonance in MATLAB"^^ . "0"^^ . . "0"^^ . . . "[Here](https://stackoverflow.com/questions/25487090/matlab-matrix-neighbour-extraction) is a simple way to convert a labeled image into a graph with the labels as nodes and edges between adjacent labels."^^ . . . "0"^^ . "2"^^ . . . "1"^^ . . . "How interesting. I've never done multithreading before, so I'll have to look into this. Thanks a bunch."^^ . "1"^^ . . "oop"^^ . . . . "3"^^ . "It's not even the advantage reasons behind it, i can’t run them separately because they are dependent: 2/ uses in its request the ID value which is produced by test 1/ successful run. This value is generated in response, so i can't set it for test 2/ by myself.\nSo, either i need to share this produced value across the tests, or store somewhere in such a way to be able to get it from there for the next tests."^^ . . . . . . . . "1"^^ . . . . "0"^^ . "<p>For each of 20 trials, I have a structure <code>S</code>, with 50 subfields. One of these subfields, <code>type</code>, is a 1x50000 structure with 50 fields. I need to add a field <code>condition</code> to the subfield structure 'type', to have <code>S.type.condition</code>.</p>\n<p><code>[S.type.condition] = deal(''); %adds the subfield to S.type</code></p>\n<p>This new subfields needs to be populated based on two of the existing subfields: <code>S.type.pres</code> (with values from 1 to 2) and <code>S.type.stimulus</code> (with values from 1 to 3), such that if</p>\n<pre><code>`S.type.stimulus == 1 &amp; S.type.pres == 1` then `S.type.condition ==1`\n`S.type.stimulus == 2 &amp; S.type.pres == 1` then `S.type.condition ==2`\n`S.type.stimulus == 3 &amp; S.type.pres == 1` then `S.type.condition ==3`\n`S.type.stimulus == 1 &amp; S.type.pres == 2` then `S.type.condition ==4`\n`S.type.stimulus == 2 &amp; S.type.pres == 2` then `S.type.condition ==5`\n`S.type.stimulus == 3 &amp; S.type.pres == 2` then `S.type.condition ==6`\n</code></pre>\n<p>I need to repeat this for each of the 20 trials.</p>\n"^^ . "0"^^ . "There are obviously two steps here: extracting the color scale from the image, and writing it out to your chosen file format. Thus, there are two questions, not one. Please ask only one question per post. The first task has already been asked many times, a Google search should point you to those previous questions."^^ . . . . "Edited it . Hope the question is more clear now."^^ . . "<p>I have also posted this question in MATLAB's forum</p>\n<p><a href="https://www.mathworks.com/matlabcentral/answers/2162625-compiler-runtime-custominstaller-fails-to-reduce-mcr-installer-size" rel="nofollow noreferrer">https://www.mathworks.com/matlabcentral/answers/2162625-compiler-runtime-custominstaller-fails-to-reduce-mcr-installer-size</a></p>\n<p>from the reply by Sumukh, it appears that <code>compiler.runtime.customInstaller</code> is basically doing the same as <code>deploytool</code>, that creates a &quot;reduce-sized&quot; mcr package using only the components returned by <code>requiredMCRProducts.txt</code>. It is simply an API version of this function - one should not expect further mcr file size reduction by calling this API.</p>\n<p>Because of this, the mcr local installer is the best matlab can produce, it is rather a coarse-grained reduction based on the components, but it currently does not support fine-grained file-level trimming.</p>\n"^^ . . . "0"^^ . . . . "<p>I use the commands:</p>\n<pre><code>dbstop if error\n</code></pre>\n<p>and</p>\n<pre><code>dbstop if warning\n</code></pre>\n<p>Is it possible to combine those conditions, to stop at either warning or error?\nAs far as I tried, the latter doesn't catch both.\nIdeally, it would look something like: dbstop if (error || warning)</p>\n"^^ . "0"^^ . "0"^^ . "0"^^ . "1"^^ . "BP neural network for digit recognition"^^ . . . "1"^^ . "1"^^ . . . . . "bluetooth"^^ . "0"^^ . "0"^^ . . . "pause"^^ . "1"^^ . . . . . . "0"^^ . . "0"^^ . . "How to add a proxy CA certificate to MATLAB"^^ . . . "1"^^ . . . . "1"^^ . . "1"^^ . "1"^^ . "<p>I want to test wether there is a correlation between the (average) exam and deliverable marks obtained by each student, so I tried to do it using resampling testing.</p>\n<pre><code>\n%% \n% Hypotheses:\n% H0​: There is no correlation between exam and deliverable marks (ρ=0).\n% H1​: There is a significant correlation between exam and deliverable marks (ρ≠0).\n\n%% \n% Calculate the observed correlation between exam and deliverable marks\nobserved_corr = corr(marks_exams_perStudent, marks_deliverables_perStudent);\n\n% Bootstrap resampling for correlation coefficients\nnResamples = 10000; % Number of bootstrap resamples\nbootstrap_corrs = zeros(nResamples, 1);\n\nfor i = 1:nResamples\n % Resample with replacement\n\n resample_indices = randi(size(marks_exams_perStudent, 1), size(marks_exams_perStudent, 1), 1);\n resample_exam = marks_exams_perStudent(resample_indices);\n resample_deliverable = marks_deliverables_perStudent(resample_indices);\n \n % Compute correlation for the resampled data\n bootstrap_corrs(i) = corr(resample_exam, resample_deliverable);\nend\n\n% Calculate the 95% Confidence Interval for the bootstrap correlations\nsorted_bootstrap_corrs = sort(bootstrap_corrs);\nlower_bound = sorted_bootstrap_corrs(floor(0.025 * length(sorted_bootstrap_corrs)) + 1);\nupper_bound = sorted_bootstrap_corrs(floor(0.975 * length(sorted_bootstrap_corrs)));\n\n% Display the confidence interval\ndisp(['The 95% Confidence Interval for the correlation coefficient is: [' num2str(lower_bound) ', ' num2str(upper_bound) ']']);\n\n\n% Calculate the p-value for the observed correlation\nbootstrap_abs_corrs = abs(bootstrap_corrs); % Take absolute values of bootstrap correlations\nobserved_abs_corr = abs(observed_corr); % Absolute value of observed correlation\n\n% Calculate the p-value (two-tailed)\np_value = mean(bootstrap_abs_corrs &gt;= observed_abs_corr);\n\ndisp(['p-value for the hypothesis test: ', num2str(p_value)]);\n\n\n</code></pre>\n<p>I get the following results:</p>\n<p>The 95% Confidence Interval for the correlation coefficient is: [0.090306, 0.50174]\np-value for the hypothesis test: 0.5187</p>\n<p>So going by CI Im able to reject the hypothesis while by p-value Im not. What am I doing wrong?</p>\n"^^ . . "0"^^ . . . . . . . . . . . "0"^^ . "I tried it out, it seems the 0 coefficients as you said are the actual numerators, such that the numbered values are b0, b2, b4, b6 and b8, while b1, b3, b5 and b7 are 0. the filter response for 4th order is very wierd, and it supposedly attenuates to -360 db, but the graphic response says otherwise, I think I'll stick to 1st or second order, thank you again. Maybe I'm misunderstanding again, but that's what testing's for."^^ . "You might want to ask about your specific use case over at [dsp.se], since you have a question about how to interpret the output of the FFT. It is not a question about programming (what this site is about)."^^ . "I expect the smallest eigenvalue to be zero. And the following should be equdistant (this is at least true in the output)."^^ . "0"^^ . . . "nan"^^ . . . "0"^^ . . "Thank you ! Using coder.extrinsic breaks the possibility to use the code generation"^^ . . "mean"^^ . . "<p>I am modeling a simulation of an APM (Automated Power Management) system where the machine adjusts its gear and RPM to react to a variable workload. I am modeling it off a tractor. So, for this model the variable workload would be increasing/decreasing resistance force the tractor has to pull.</p>\n<p>I am stuck with the gearbox. I have the code determining wheel torque required, and I need to do an inverse table lookup. The table is set up like f(x,y)=z where x=Throttle Position/RPM, y=Gear and z=Wheel Torque. In this instance I know my throttle position, and I know torque required, I need a way for it to give me the corresponding gear.</p>\n<p>Here's what the table looks like:</p>\n<p><img src="https://i.sstatic.net/JcQXqc2C.png" alt="table" /></p>\n<p>I know how to use the 2-D table look up to find z from x and y, but not to find y with x and z.</p>\n"^^ . . . . "Reverse 2-D table lookup"^^ . . . "0"^^ . "How can I improve my MATLAB code to isolate a QR code from images with various elements in their backgrounds?"^^ . . "Yes, you would have to generate the graph by finding the labels that are adjacent. Tedious, but not difficult given a labeled image."^^ . . . "<p>I'm currently working on a project that involves isolating QR codes from images that contain various background elements. But I'm struggling to figure out how to isolate the QR code from the background.</p>\n<p><a href="https://i.sstatic.net/BH4sQgAz.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BH4sQgAz.jpg" alt="QR code image - QR01" /></a></p>\n<p><a href="https://i.sstatic.net/IYEpkxfW.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IYEpkxfW.jpg" alt="QR code image - QR02" /></a></p>\n<p>The images below show my attempt so far, but I've only managed to isolate the 3 corner squares and some white parts of the QR code. Although some of the isolated regions have unwanted artifacts.</p>\n<p>I'm very new to image processing so I'm learning how to use these image processing function while working on this project, so please excuse any simple mistake I've made.</p>\n<p>The challenges:</p>\n<ul>\n<li>The isolated region includes unwanted artifacts.</li>\n<li>I'm unsure if my structuring element is appropriate for the morphological operations for extracting QR codes.</li>\n<li>I've experimented with different threshold values, but the results vary significantly.</li>\n</ul>\n<p>Request for Feedback:</p>\n<ul>\n<li>Could someone provide insights on how to improve my morphological processing? Are there any specific techniques or adjustments you would recommend to better isolate the QR code patterns from the background image?</li>\n</ul>\n<p>My MATLAB code:</p>\n<pre><code>% Read the input image\nimg = imread('QR01.jpg');\n\n% Convert to grayscale if the image is RGB\nif size(img, 3) == 3\n img = rgb2gray(img);\nend\n\n% Set a threshold to create a binary image\nthresholdVal = 0.5; % Adjust as necessary\nthreshold_img = imbinarize(img, thresholdVal);\n\n% Morphological operations to emphasize squares\nse = strel('square', 5); % Use a smaller structuring element to preserve finer details\ncleaned_img = imopen(threshold_img, se); % Remove small noise\n\n% Identify connected components in the cleaned image\nbConnectedComponents = bwconncomp(cleaned_img, 4);\nstats = regionprops(bConnectedComponents, 'Area', 'BoundingBox', 'Eccentricity', 'Extent');\n\n% Initialize a blank image for the QR code\nqrCodeRegion = false(size(cleaned_img));\n\n% Loop through each component to find potential QR patterns\nfor k = 1:bConnectedComponents.NumObjects\n area = stats(k).Area;\n bbox = stats(k).BoundingBox;\n aspectRatio = bbox(3) / bbox(4); % Width / Height ratio\n extent = stats(k).Extent; % Ratio of area to bounding box area\n\n % QR finder patterns are approximately square with high extent (~1 for solid shapes)\n if area &gt; 100 &amp;&amp; area &lt; 1000 &amp;&amp; aspectRatio &gt; 0.8 &amp;&amp; aspectRatio &lt; 1.2 &amp;&amp; extent &gt; 0.6\n % Mark this component as part of the QR code\n qrCodeRegion(bConnectedComponents.PixelIdxList{k}) = true;\n end\nend\n\n% Further dilation if needed to connect the finder patterns\n%qrCodeRegion = imdilate(qrCodeRegion, strel('square', 10));\n\n% Show the isolated QR code region\nfigure;\nimshow(img);\ntitle('Original QR Code image');\n\nfigure;\nimshow(qrCodeRegion);\ntitle('Isolated QR Code Region');\n</code></pre>\n<p><a href="https://i.sstatic.net/c7HeZvgY.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c7HeZvgY.jpg" alt="Original QR Code image" /></a></p>\n<p><a href="https://i.sstatic.net/AFr7nq8J.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AFr7nq8J.jpg" alt="Isolated QR Code Region" /></a></p>\n"^^ . "0"^^ . "0"^^ . . "2"^^ . "1"^^ . . "From [the docs](https://www.mathworks.com/help/matlab/matlab_prog/class-based-unit-tests.html#mw_c7446675-bdbf-4178-9e33-ead315793a26): “Unit tests in a matlab.unittest.TestCase subclass must run independently, without unintentionally affecting one another. In addition, they must be repeatable, which means that a running test must not affect subsequent reruns of the same test.”"^^ . "2"^^ . "1"^^ . "@PeterCordes I don't think MATLAB would disclose that information so I fill the gap with some guesswork. I understand you have been following this topic for a while, so feel free to edit the answer."^^ . . . . "1"^^ . "1"^^ . . . "random"^^ . "1"^^ . . . "toolbox"^^ . . "0"^^ . . "0"^^ . "this might be better asked on the [dsp.se] SE -- this question came from the [staging ground](https://stackoverflow.com/staging-ground/79216322)"^^ . . . "0"^^ . . . . . . "Find column indices of a matrix entries that are repeated values"^^ . . . . "1"^^ . "1"^^ . . . . . . "multi-gpu"^^ . "1"^^ . "1"^^ . "I want to compute FFT and IFFT on a large image via GPU. But my GPU is low on memory"^^ . . "3"^^ . . "1"^^ . "<p>Assigning to your local variable <code>report_id</code> makes the UUID literal type <code>text</code> effectively.</p>\n<p>Your second attempt is missing a <code>FROM</code>:</p>\n<pre><code>query = "SELECT * <b>FROM</b> public.fn_func($1::uuid)";</code></pre>\n<p>But you should really get this error:</p>\n<blockquote>\n<p>ERROR: syntax error at or near &quot;public&quot;</p>\n</blockquote>\n<p>If that does not fix it, then I am not sure how your client manages to thwart the query.</p>\n<p>You could create an (overloaded?) function taking <code>text</code> and cast in the function (like Adrian commented), or you could concatenate the query string with an untyped literal:</p>\n<pre><code>query = &quot;SELECT * FROM public.fn_func('5ed30f08-0de0-47f4-99e8-9aeeb8eb2dfe')&quot;;\n</code></pre>\n<p><a href="https://dbfiddle.uk/QRxFvsAd" rel="nofollow noreferrer">fiddle</a></p>\n"^^ . "0"^^ . . . "0"^^ . . "0"^^ . . "0"^^ . . . . . . . . . "0"^^ . "0"^^ . . "0"^^ . "code-generation"^^ . . . "@beaker I would not need an alpha for my use scenario"^^ . . . "TeX formatting doesn't work here to render maths"^^ . . "You intend for `result` to be a single value, sum of all `outcome`? Because `outcome:outcome(100)` is an array with all integer values in between `outcome(1)` and `outcome(100)`, if both of them are integers, the other values in `outcome` would be ignored. I think you meant to do `outcome(1:100)`. What is `plot result` meant to do? `outcome(i)=randsample(sample,1);` would work if `sample` is defined as a numeric array as @wolfie suggested."^^ . . "<p>@Irreducible is correct. You have created filter coefficients that expose a numerical stability issue in the case of a 4th order Butterworth filter. See here for an explanation: <a href="https://en.wikipedia.org/wiki/Digital_filter#Direct_form_II" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Digital_filter#Direct_form_II</a></p>\n<p>Basically, DFII is a highly optimized implementation of a time domain convolution, but since the poles are calculated first, the gain can go extremely high, extremely fast and lead to numerical instability, especially in the case of high Q filters (which yours is an example of).</p>\n<p>Also, not sure why you see only 5 values for your <code>b</code>s, but scipy.signal.butter always returns the same number of coefficients for <code>b</code> and <code>a</code>.</p>\n<p>As suggested, express the filter as second order sections and your filter will be fine:</p>\n<pre><code>import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfs=20000\nbt,at= signal.butter(4,[7.692307692307693,13],'bandpass',fs=fs)\nb1,a1= signal.butter(1,[7.692307692307693,13],'bandpass',fs=fs)\n\nt = np.linspace(0, 1, fs, endpoint=False)\nfreq = 10\nsqr_wave = signal.square(2 * np.pi * 10 * t)\nplt.plot(t, sqr_wave,label='orig')\nsqr_wave_1st_order = signal.lfilter(b1, a1, sqr_wave)\nplt.plot(t, sqr_wave_1st_order,label='1st order')\nsqr_wave_4th_order = signal.lfilter(bt, at, sqr_wave)\nplt.plot(t, sqr_wave_4th_order,label='4th order ba')\nsos_4th_order = signal.butter(4,[7.692307692307693,13],'bandpass',fs=fs,output='sos')\nsqr_wave_sos = signal.sosfilt(sos_4th_order, sqr_wave)\nplt.plot(t, sqr_wave_sos,label='4th order sos')\nplt.ylim(-2, 2)\nplt.legend()\nplt.show()\nprint(bt)\nprint(at)\n</code></pre>\n<p>Output:</p>\n<pre><code>[ 4.82121714e-13 0.00000000e+00 -1.92848686e-12 0.00000000e+00\n 2.89273028e-12 0.00000000e+00 -1.92848686e-12 0.00000000e+00\n 4.82121714e-13]\n[ 1. -7.99560326 27.96927189 -55.90796275 69.84684949\n -55.84709416 27.90840316 -7.96951656 0.99565219]\n[ 0.00083304 0. -0.00083304]\n</code></pre>\n<p><a href="https://i.sstatic.net/TpNREZuJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TpNREZuJ.png" alt="enter image description here" /></a></p>\n<p>To implement your SOS filter, you basically take your set of biquads (output of ouptut='sos') and stack the filters back to back. Julius Smith has a succinct explanation: <a href="https://ccrma.stanford.edu/%7Ejos/fp/Series_Second_Order_Sections.html" rel="nofollow noreferrer">https://ccrma.stanford.edu/~jos/fp/Series_Second_Order_Sections.html</a>.</p>\n"^^ . . "<p>This is explained in <a href="https://www.mathworks.com/help/matlab/matlab_env/where-matlab-stores-preferences.html" rel="nofollow noreferrer">this documentation page</a>. In short, the function <code>prefdir</code> returns the path to where preferences are stored.</p>\n<p>In Linux this is <code>~/.matlab/&lt;release&gt;</code>. It being a hidden directory explains why your <code>find</code> command didn’t find it.</p>\n<p><strike>If you fail to find the right file where this configuration is stored in, you can always add your <code>jenv</code> command to your <a href="https://www.mathworks.com/help/matlab/ref/startup.html" rel="nofollow noreferrer"><code>startup.m</code></a> file.</strike> [Doesn't work in this case because changing the Java environment used requires restarting MATLAB.]</p>\n<hr />\n<p>In the preferences directory, there's a file called <code>matlab.mlsettings</code>. This is a ZIP file. Once unzipped, you'll find a JSON file at <code>fsroot/settingstree/matlab/external/interfaces/java/maca64/settings.json</code> (the <code>maca64</code> part is for macOS, on Linux this will likely be <code>glnxa64</code> instead of <code>maca64</code>). This JSON file has a bit that reads</p>\n<pre class="lang-none prettyprint-override"><code>&quot;name&quot;:&quot;JrePath&quot;,&quot;value&quot;:&quot;&lt;path&gt;&quot;\n</code></pre>\n<p>My guess is that you can edit the path there, zip up the directory again, and replace the original <code>matlab.mlsettings</code> file.</p>\n"^^ . . "data-analysis"^^ . . "ubuntu-22.04"^^ . "0"^^ . . . . "1"^^ . "0"^^ . "0"^^ . . . . . "0"^^ . . . . "Your callback ```fileLoad1Callback``` doesn't know anything about the variables in ```selectLoad```. While you can assign characters to a struct ```fileLoad1.Text``` it doesn't do anything to your button. Inside ```fileLoad1Callback``` just replace ```fileLoad1.Text``` with ```src``` (which is your button object) and it should work."^^ . . . . . . "0"^^ . "0"^^ . . . . . "0"^^ . . . "0"^^ . "How to import MATLAB datetime array into python?"^^ . "Matlab/Simulink Parallel Computing with Initialization Scripts"^^ . "<p>You could take advantage of some thread/process management routines. Something along the lines of:</p>\n<pre><code>% Create a thread pool\npool = parpool('Threads');\n\n\n% Submit the tasks to the thread pool\nfuture1 = parfeval(pool, @countToN, 0, 10);\nfuture2 = parfeval(pool, @countToN, 0, 1000);\n\n% Periodically check if any of the threads have finished\nwhile ~strcmp(future1.State,'finished') &amp;&amp; ~strcmp(future2.State,'finished')\n pause(0.1); % Check every 100ms\n disp(&quot;checking stats&quot;)\n if strcmp(future1.State,'finished')\n fprintf('Task 1 finished, cancelling Task 2.\\n');\n future2.cancel();\n elseif strcmp(future2.State,'finished')\n fprintf('Task 2 finished, cancelling Task 1.\\n');\n future1.cancel();\n end\nend\n\n% Wait for both tasks to finish (in case they were cancelled)\nwait([future1, future2]);\n\n% Clean up the thread pool\ndelete(pool);\n\nfunction countToN(n)\nfor i = 1:n\n fprintf('Counting to %d: %d\\n', n, i);\n pause(0.1); % 10ms delay\nend\nend\n</code></pre>\n"^^ . "Note that `max(max(A))` for 2D `A` is more efficiently written as `max(A(:))`. In recent versions of MATLAB you can also do `max(A,[],'all')`."^^ . . . . . . . "The second factor inside the curly braces is missing a Fourier transform, isn't it?"^^ . . "0"^^ . "How can I make the mean of 3d matrices in a cell in Matlab?"^^ . "1"^^ . . . "All your loop indices can change (by tiny amounts) when you change the end point. You might find this explanation interesting: https://stackoverflow.com/questions/49377234/how-does-the-colon-operator-work-in-matlab -- You should always use integers as loop indices, if you care about reproducibility and precision."^^ . . . "1"^^ . . . "As I see it: Every numerical approach is always an approximation. And thus scaling the system *will* give different results. But still: The same way my, say, 4th-order-method will (up to a certain point) converge to the real solution with O(h^4) it should be possible to say: "If I scale down my system by a factor of 2, I will have to increase my relTol by X and my absTol by Y to get comparable results with comparable effort". All that of course only to a certain point (simulating masses that are lightyears apart over millions of years might fail because of cancellation if I *don't* scale down)"^^ . . "time"^^ . "Are you wondering what would happen on a CPU with only E-cores, no P-cores, like Alder Lake N, or Xeon 6 Sierra Forest? Or a VM that had only E cores? IDK, hopefully it doesn't report 0 in that case :P"^^ . . "<p>It is known that modern CPUs have both Performance cores (P-cores) and efficiency cores (E-cores), different types of CPU cores that have different purposes and are designed for different tasks. P-cores typically have higher clock speeds and designed for high-performance tasks, while E-cores operate at lower clock speeds and focus on energy-efficient processing.</p>\n<p>In MATLAB, maxNumCompThreads returns the current maximum number of computational threads. Currently, the maximum number of computational threads is equal to the number of physical cores on your machine.</p>\n<p>How MATLAB makes the distinction between P-Cores and E-Cores ?</p>\n<p>Brahim @ Singapore</p>\n"^^ . . . . . . . . . . . . . "linear-equation"^^ . . . . . . . . "field"^^ . . . "<p>The error you get is quite explicit, and tells you to try using <code>str2sym</code>:</p>\n<blockquote>\n<p>Error using sym&gt;convertChar (line 1557)</p>\n<p>Character vectors and strings in the first argument can only specify a variable or number. <strong>To evaluate character vectors and strings representing symbolic expressions, use 'str2sym'.</strong></p>\n</blockquote>\n<p>Doing that gives us an output of <code>0</code>, so we should heed the <a href="https://stackoverflow.com/questions/79138918/represent-tiny-numbers-in-matlab-using-sym-and-vpa#comment139547064_79138918">comment from Cris</a> and use <code>10^</code> instead of <code>1e</code>, as well as <code>str2sym</code>:</p>\n<pre><code>x=str2sym('-10^(-10^308)')\n</code></pre>\n<p>That gives us a different error:</p>\n<blockquote>\n<p>Error using str2sym (line 66)</p>\n<p>Unable to convert string to symbolic expression:\nInteger too large in context.</p>\n</blockquote>\n<p>This has <a href="https://uk.mathworks.com/matlabcentral/answers/141712-error-in-expand-bigprod-integer-too-large-in-context" rel="nofollow noreferrer">already been asked about elsewhere</a></p>\n<p>Quoting the MathWorks staff member from the linked post:</p>\n<blockquote>\n<p>This error means the computation is trying to compute something like integer^integer with an exponent larger than 2^32. The resulting integer would take up several Gigabytes of memory and take a long time to compute – and be pretty much useless for virtually all applications. So the symbolic engine flat out refuses to start computing it.</p>\n</blockquote>\n<hr />\n<p>Aside: I would take a moment to consider if you actually require both exponents, that would be an <em>incredibly</em> tiny number (or large if the exponent sign was positive), even <code>10^(10^10)</code> is large enough for the symbolic math engine to refuse creation...</p>\n"^^ . . . "0"^^ . "3"^^ . . . . . . . . . . . . "You're passing a character array (the file name) to `size`. The actual file name you're using is probably 49 characters long. You probably want to use [`niftiread`](https://www.mathworks.com/help/images/ref/niftiread.html) to read your file and put the data in a variable. Then use that variable in the two places where you have the file name in your code."^^ . . . . . . "0"^^ . . "1"^^ . . "0"^^ . "<p>In Matlab, I have given a network in the MATPOWER case file format (see the MATPOWER doc).</p>\n<p>I now want to check, if it is AC-feasible. To that end, I employed <code>runpf</code> (see the MATPOWER doc):</p>\n<pre><code>define_constants;\nmpc = loadcase(case_file_path);\nresults = runpf($mpc);\n</code></pre>\n<p>On most of my cases, I got the result that it is feasible. Now I wanted to check the branch violations of the infeasible ones. However, I noticed that there are also branch violations on the ones that are marked as feasible (which for me does not make sense from a physical POV).</p>\n<p>I calculated the violations as follows:</p>\n<pre><code>pfs = results.branch(:, PF);\nqfs = results.branch(:, QF);\npts = results.branch(:, PT);\nqts = results.branch(:, QT);\nSfs = sqrt(pfs.^2 + qfs.^2);\nSts = sqrt(pts.^2 + qts.^2);\nactive = mpc_target.branch(:, 11) &gt; 0.5;\nrates = mpc_target.branch(:, 6); % the 6th column gives the rateA of the branch \nviolations_n = sum((Sfs .* active &gt; rates) | (Sts .* active &gt; rates));\n</code></pre>\n<p>My guess is that the function does not enforce the limits in the network, but that is what I need.</p>\n<p>What I tried so far:</p>\n<p>In the description of <code>runpf</code> it is mentioned, that the <code>pf.enforce_q_lims</code> option exists. I tried to set it to true (in the hope that this will somehow lead to an adherence of the flow limits as well), but the result remained unchanged.</p>\n<p>I found another function <code>runcpf</code>. This function DOES have the option <code>cpf.enforce_flow_lims</code>. However, the function seems to perform a continuation power flow, which I am guessing is not what I want since I need a base case and a target case (I am not an electrical engineer, so I have limited knowledge). Nevertheless, I ran the function (with both cases being the base case and the aforementioned option activated), but the result remained the same: the same violations occurr.</p>\n<p>I am unsure how to proceed. Is this simply not possible with MATPOWER due to restriction I am not aware of? This seems impractical to me however.</p>\n"^^ . . "debugging"^^ . "mathematical-optimization"^^ . "You're also setting `Q(i,:)=[k_1,k_1]` when there is only one instance of `i`, is that what you want? Will there ever be an instance where the two columns are different, or is `Q(:,1) == Q(:,2)`? Are all of the integers `[1:max(max(A))]` guaranteed to appear?"^^ . "2"^^ . "0"^^ . . . . . . . "<p>I have an inverse kinematics solver. I want to bias one joint angle value to at least approach a certain value wherein this angle will result in the link to be flat or parallel to the ground. The script runs well but my problem is fmincon stops the iteration, I think, once the default TolFun value is reached. The bias value is around +-0.17 radians or +- 10 degrees.</p>\n<p>I've tried using a very small TolFun value such as 1e-12 but it when an iteration converges, the angle I want to bias still does is not reach the desired value or close to it. I tried adding an fval threshold and using while loop but I think the TolFun stopping criterion still supersedes that since whan I run the script, almost similar convergence are reached. I need some help in how to implement the biasing. Here is the code snippet:</p>\n<pre><code>function A = transformation_matrix(theta, alpha, a, d)\n A = [[cos(theta), -cos(alpha) * sin(theta), sin(alpha) * sin(theta), a * cos(theta)];\n [sin(theta), cos(alpha) * cos(theta), -sin(alpha) * cos(theta), a * sin(theta)];\n [0, sin(alpha), cos(alpha), d];\n [0, 0, 0, 1]];\n end\n\nfunction position = forward_kinematics(joint_angles)\n theta2 = joint_angles(1);\n theta3 = joint_angles(2);\n theta4 = joint_angles(3);\n theta5 = joint_angles(4);\n theta6 = joint_angles(5);\n\n A1 = transformation_matrix(0, 0, 0, 148);\n A2 = transformation_matrix(theta2, pi/2, 0, 152);\n A3 = transformation_matrix(theta3, 0, 250, 0);\n A4 = transformation_matrix(theta4, 0, 160, 0);\n A5 = transformation_matrix(theta5+pi/2, pi/2, 0, 0);\n A6 = transformation_matrix(theta6, 0, -75, 160);\n\n position_matrix = A1 * A2 * A3 * A4 * A5 * A6 * [0; 0; 0; 1];\n %threshold = 1e-8; % Small threshold to round off to zero\n %position_matrix(abs(position_matrix) &lt; threshold) = 0; % Set small values to zero\n position = position_matrix(1:3);\nend\n\nfunction error = objective_function(joint_angles, target, initial_guess, is_first_run)\n theta3 = joint_angles(2);\n theta4 = joint_angles(3);\n theta5 = -(theta3+theta4);\n\n position = forward_kinematics(joint_angles);\n error = norm(position - target);\n bias_theta5=abs(joint_angles(4)-theta5);\n disp('Theta 5 bias:');\n disp(bias_theta5);\n error += 1*bias_theta5 %bias to land theta5 close to a value that parallel with the origin Y-coord\n if ~is_first_run\n error += 0.1 * norm(joint_angles - initial_guess); % Penalize deviation from initial guess\n end\nend\n\nfunction error = objective_function(joint_angles, target, initial_guess, is_first_run)\n theta3 = joint_angles(2);\n theta4 = joint_angles(3);\n theta5 = -(theta3 + theta4);\n\n position = forward_kinematics(joint_angles);\n error = norm(position - target);\n bias_theta5 = abs(joint_angles(4) - theta5);\n\n disp('Theta 5 bias:');\n disp(bias_theta5);\n\n error += 1 * bias_theta5; % Bias to land theta5 close to the value parallel with the origin Y-coord\n\n if ~is_first_run\n error += 0.1 * norm(joint_angles - initial_guess); % Penalize deviation from initial guess\n end\nend\n\nfunction [joint_angles, exitflag] = inverse_kinematics(target_position, initial_guess, is_first_run)\n options = optimset('Display', 'final', 'MaxIter', 2000); % Omitting 'TolFun'\n\n % Constraints for initial values for the first four angles\n initial_lb = [-(5/6) * pi; -(1/6) * pi; -(11/18) * pi; -(1/2) * pi];\n initial_ub = [ (5/6) * pi; (5/9) * pi; 0; (1/2) * pi];\n\n if is_first_run\n lb = initial_lb; % Use the initial lower bounds\n ub = initial_ub; % Use the initial upper bounds\n else\n % Update bounds based on the converged joint angles\n lb = initial_lb - initial_guess(1:4); % Subtract converged values\n ub = initial_ub - initial_guess(1:4); % Subtract converged values\n end\n\n initial_guess_4 = initial_guess(1:4);\n %max_iter = 100; % Set a maximum number of iterations\n fval_threshold = 0.17; % Stopping criterion for fval\n iter = 0;\n converged = false;\n\n while ~converged %&amp;&amp; iter &lt; max_iter\n % Optimize theta2, theta3, theta4\n [joint_angles_4, fval, exitflag] = fmincon(@(j) objective_function([j; 0], target_position, initial_guess, is_first_run), ...\n initial_guess_4, [], [], [], [], lb, ub, [], options);\n\n % Check the stopping criterion based on fval\n if fval &lt; fval_threshold\n converged = true; % We have reached the desired fval\n end\n\n initial_guess_4 = joint_angles_4; % Update initial guess for next iteration\n %iter = iter + 1;\n end\n\n joint_angles = [joint_angles_4; 0]; % Set theta 6 to zero\n\n % Display result\n if converged\n fprintf('Converged with fval: %f\\n', fval);\n else\n fprintf('Maximum iterations reached without achieving desired fval.\\n');\n end\nend\n</code></pre>\n"^^ . . "RTW Embedded coder generating #includes in C file instead of H file"^^ . "The missing `from` was my bad, I was trying to anonymize the query a bit and deleted that."^^ . . "0"^^ . . . . "0"^^ . "parallel-processing"^^ . . . "1"^^ . . "Im trying to plot a Airfoil using matlab and want a sharp edge but i cant figure it out"^^ . . . "Load Flow Analysis Issue in IEEE 34-Bus Model on MATLAB Simulink"^^ . . "0"^^ . . "0"^^ . . . . . "<p>Is there an aggregate array function in Matlab similar to <a href="https://support.google.com/docs/answer/12568597?hl=en" rel="nofollow noreferrer"><code>reduce</code></a> in Google Sheet or <a href="https://docs.racket-lang.org/reference/pairs.html#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldr%29%29" rel="nofollow noreferrer"><code>foldr</code></a> in Racket?</p>\n<p>For example, the other day, I was hoping to extract/exclude a row representing every third week of the month,</p>\n<div class="s-table-container"><table class="s-table">\n<thead>\n<tr>\n<th><code>isnumeric()</code> =&gt; true</th>\n<th><code>isnumeric()</code> =&gt; true</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>202211</td>\n<td>data_to_be_aggregated_type_1</td>\n</tr>\n<tr>\n<td>202211</td>\n<td>data_to_be_aggregated_type_1</td>\n</tr>\n<tr>\n<td>202211</td>\n<td>data_to_be_aggregated_type_2</td>\n</tr>\n<tr>\n<td>202211</td>\n<td>data_to_be_aggregated_type_1</td>\n</tr>\n<tr>\n<td>202211</td>\n<td>data_to_be_aggregated_type_1</td>\n</tr>\n<tr>\n<td>202212</td>\n<td>data_to_be_aggregated_type_1</td>\n</tr>\n<tr>\n<td>202212</td>\n<td>data_to_be_aggregated_type_1</td>\n</tr>\n<tr>\n<td>202212</td>\n<td>data_to_be_aggregated_type_2</td>\n</tr>\n<tr>\n<td>202212</td>\n<td>data_to_be_aggregated_type_1</td>\n</tr>\n</tbody>\n</table></div>\n<p>I ended up copying the data to Google Sheet, where the data can be processed with one (local) function, and only then copied to Matlab</p>\n<p>As well, in the above example, it is necessary(?) to be able to reference a different index based on a preset offset from the current index. In order to tell whether a row represents the 3rd week of a month, one way is to, for example, check whether month digits are different from 3 rows before but the same as 2 rows before. Google Sheet allows for this via <a href="https://support.google.com/docs/answer/3093379?hl=en" rel="nofollow noreferrer"><code>offset</code></a>. (Google Sheet <code>reduce</code> also only accepts 1D array as argument, further increasing the need for <code>offset</code>.)</p>\n<p>So.. Is there an Matlab equivalent for <code>reduce</code> or <code>foldr</code> and the corresponding tools such as <code>offset</code>?</p>\n"^^ . . . "The error message is pretty clear about the solution: “Please install the correct version of the MATLAB Runtime.” [The documentation for MATLAB Compiler](https://www.mathworks.com/help/compiler/index.html) is also pretty clear: “End users can run your applications royalty-free using MATLAB Runtime.” See here for more information on the runtime: https://www.mathworks.com/help/compiler/matlab-runtime.html"^^ . . . "1"^^ . . "<p>How can I find the row reduced form of a symbolic matrix with matlab. I have the symbolic toolkit installed and looking at the documentation it says to just use the rref function like normal. However, this doesn't seem to work properly.</p>\n<p>Example</p>\n<pre><code>syms h\nM = [\n1 h\n2 3]\nrref(M)\n</code></pre>\n<p>This results in</p>\n<pre><code>[1, 0]\n[0, 1]\n</code></pre>\n<p>However I would expect the answer to be closer too</p>\n<pre><code>[1, h]\n[0, 3-2*h]\n</code></pre>\n<p>How do I do this? Other operations (add, subtract, det) work fine with symbolic matrices. Is there a different command to use? Or is this just not possible?</p>\n<p>Thanks</p>\n"^^ . "The link to access the Excel file is now working."^^ . . "0"^^ . . . "4"^^ . "0"^^ . . "2"^^ . . "@LuisMendo added, `im2col` is curiously noisy too compared to the other methods - added to the benchmark above"^^ . "Is "some number" the same for all entries that need to be modified? If not, what is the rule to compute that number?"^^ . "0"^^ . . . "ros2"^^ . . "1"^^ . "0"^^ . "0"^^ . . . . . . . . "0"^^ . "Hi Cris, this is a minimum reproducible example, which generates the test data, runs the analysis, then plots the outputs, including the linear discriminant for reference. Whilst there's no error code, the issue is clear, the boundaries between the groups just aren't present on figure 2. So, something is wrong with how I'm plotting figure 2, at the very end of the code sample. Could be as simple as "evaluating the coeffs incorrectly", which was the issue with the 3d question I posted, but I can't for the life of me figure out how to correct it for this."^^ . . "0"^^ . . "<p>I'm using fir2 function (and then filter with basic settings filter(fir2,1,audio) ) to filter audio files to specific values in each spectrum band. I have two sets of dB values:</p>\n<ul>\n<li>the original spectrum of a file</li>\n<li>the final spectrum I want the file to be</li>\n</ul>\n<p>I've tried taking the difference between the two levels and un&quot;log&quot; it like that:</p>\n<pre><code>20^(FdB SPL - OdB SPL/20)\n\nFdB - final level\nOdB - original level\n</code></pre>\n<p>For example for a 125Hz band filter magnitude would be 20^(38-35/20) = 1.995</p>\n<p>Then I would take these values and use them as magnitude for the fir2. I'm using 50nth order. It didn't seem to work properly, or it worked with various accuracy in different files. I'm using Artemis to calculate all the dB values with the function &quot;1/n Octave Spectrum (FFT) (4096; 50%)&quot;. I'm using wav format for files. I probably messed something simple, like about the formula, but at this point I'd rather look like a dummy for not knowing something trivial instead of brute forcing it.</p>\n<pre><code>[audio,fs] = audioread(append(filename,&quot;.wav&quot;)) ;\n\nf = [0 0.0004535147392 0.000566893424 0.0007256235828 0.0009070294785 0.001133786848 0.001428571429 0.001814058957 0.002267573696 0.002857142857 0.003628117914 0.004535147392 0.00566893424 0.007256235828 0.009070294785 0.01133786848 0.01428571429 0.01814058957 0.02267573696 0.02857142857 0.03628117914 0.04535147392 0.0566893424 0.07256235828 0.09070294785 0.1133786848 0.1428571429 0.1814058957 0.2267573696 0.2857142857 0.3628117914 0.4535147392 0.566893424 0.7256235828 0.9070294785 1];\n\nm = [1 0.88180561540975 0.881805363482077 0.835826382716575 0.776642454832629 0.759436720529334 0.653244752807778 0.745167995891424 0.850117073913788 0.98912260419711 0.960201464902893 0.923199850846219 1.13897797703032 0.874874253414851 1.13953780367958 1.28584396648708 0.67694058247949 0.785826825740988 1.00665129584544 1.38588097381939 1.59663824625406 1.46013949870038 1.55967029805846 1.57082839521638 1.96165693766572 1.74722265683908 1.77693364984782 1.29579584587398 1.58136046978984 1.69990075644448 1.42024073863697 1.91114522246185 1.55168355673292 1.00086374398705 1.0301145684381 1];\n\nb = fir2(50, f, m6);\nA = 1;\nY = filter (b, A, audio);\n\namp = 0.06309573445\nY_new=Y*amp/rms(Y);\n\nnewname = append(&quot;f_&quot;,&quot;_&quot;,filename,&quot;.wav&quot;);\naudiowrite (newname, Y_new, fs,'BitsPerSample',32);\n</code></pre>\n"^^ . "I was reluctant to take the last approach since it involves learning a new tool and integrating it into my CI Pipeline, but I'm now thinking its the best option. I have about 30 functions."^^ . "3"^^ . . "qt-quick"^^ . "mser"^^ . . . . . . . . "3"^^ . . "least-squares"^^ . "0"^^ . . "r"^^ . . "In my case T was of shape (height,width,numClasses,batchSize, so I had to change T==i to T(:,:,i,:). Other than that, it worked perfectly"^^ . . . . . . . "0"^^ . "Glad I could help for such a beautiful application!"^^ . . "<div class="s-table-container"><table class="s-table">\n<thead>\n<tr>\n<th>ID</th>\n<th>Channel</th>\n<th>relativeAlpha</th>\n<th>relativeBeta</th>\n<th>relativeGamma</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>01-12</td>\n<td>F7</td>\n<td>9.25</td>\n<td>1.23</td>\n<td>2.98</td>\n</tr>\n<tr>\n<td>01-12</td>\n<td>F8</td>\n<td>8.35</td>\n<td>3.45</td>\n<td>6.78</td>\n</tr>\n</tbody>\n</table></div>\n<p>I'm using EEG lab to calculate relative spectral power for various bands. This went well, but now I'm stuck on how to reshape this the way I need it. I have 20 participants, and I want each participant to have only one row of data.</p>\n<p>As such, I'm trying to convert this matrix so that the columns are a combination of electrode and frequency band. For example, each participant would have one row of data with columns labelled F7.relativeAlpha, F7.relativeBeta, and so on (see below for example). Any help would be greatly appreciated!</p>\n<div class="s-table-container"><table class="s-table">\n<thead>\n<tr>\n<th>ID</th>\n<th>F7.relativeAlpha</th>\n<th>F7.relativeBeta</th>\n<th>F7.relativeGamma</th>\n<th>F8.relativeAlpha</th>\n<th>F8.relativeBeta</th>\n<th>F8.RelativeGamma</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>01-12</td>\n<td>9.25</td>\n<td>1.23</td>\n<td>2.98</td>\n<td>8.35</td>\n<td>3.45</td>\n<td>6.78</td>\n</tr>\n</tbody>\n</table></div>\n<p>I've tried unsuccessfully with the reshape function and with the unstack function.</p>\n<pre><code>RelativePowerWide = unstack(RelativePowerResults,'ID','RelativeDelta')\n</code></pre>\n"^^ . . . "2"^^ . . "scripting"^^ . "<p>I have a data table with three columns:</p>\n<pre><code>t = [\ndatum,meter-reading,meter-exchange\n25-Sep-2012,2.6,0\n13-Oct-2013,12.0,0\n28-Oct-2013,14.4,0\n01-Nov-2013,14.2,1\n12-Dec-2013,0.1,0\n23-Feb-2014,0.9,0\n15-Jun-2014,3.0,0\n15-Sep-2014,6.0,0\n23-Jun-2015,8.7,0\n06-Oct-2015,10.2,0\n...\n]\n</code></pre>\n<p>Is there any neat way to create a new table (matrix) where the yearly consumption is calculated with the meter-readings including possible meter changes (meter exchanged &quot;1&quot; in column 3).</p>\n<p>The consumption is calculated by the difference of the latest meter reading in one year and the latest meter reading in the year before. But when the meter is exchanged the consumption is calculated slightly differently (if change is &quot;1&quot;, take difference from the meter reading of that date with last meter reading of the year before plus the last meter reading of the same year.</p>\n<p>Expected result is (ignoring first year 2012):</p>\n<pre><code>t1 = [\nyear,consumption\n2013,11.7\n2014,5.9\n2015,4.2\n...\n]\n</code></pre>\n"^^ . . "3"^^ . "MATLAB Neural Network Predictions Converging to 1"^^ . "0"^^ . . "<p>It seems that in</p>\n<blockquote>\n<p><code>outerFunc(innerFunc, [2, 4, 5]) % doesn't work</code></p>\n</blockquote>\n<p>you intend to <strong>pass</strong> <code>innerFunc</code> as an input to <code>outerFunc</code>. However, what that line does is <strong>call</strong> <code>innerFunc</code> (which gives an error because the input to that function is missing); and the output of that function call would then be used as input to <code>outerFunc</code>.</p>\n<p>To pass (a handle of) <code>innerFunc</code> as an input to <code>outerFunc</code> you need to prepend <code>@</code> (more information <a href="https://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html" rel="noreferrer">here</a>):</p>\n<pre><code>outerFunc(@innerFunc, [2, 4, 5])\n</code></pre>\n"^^ . . . . "1"^^ . "graph-theory"^^ . "0"^^ . . "2"^^ . . "1"^^ . . "@ThomasIsCoding, I don’t have access to MATLAB at the moment to try it, but could you try the effect of making the bottom-right element of the matrix 0.57735027-0.5j (i.e. non-zero imaginary part) and see if that would give the vector that the OP writes for MATLAB. This is what a hand calculation suggests might be the original fault."^^ . . "<p>=== Simulation (Elapsed: 3 sec) ===\npulse =\n1\nError:An error occurred while running the simulation and the simulation was terminated\nCaused by:\nDerivative of state '1' in block 'chargecontrol/PV Array/Diode Rsh/Transfer Fcn' at time 0.0 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)</p>\n<p>I tried to change the tolerance sample time but it did not work and I tried a constant DC source and it is working. I have put the irradiation and temperature constant too.</p>\n"^^ . . "numerical-methods"^^ . "<p>I don't think you should be bothered by the deviations among different programming languages. The difference might be caused by the precision of number representation, the algorithm under the hood, the hidden configuration of functions and so on. The only thing that matters is: <em><strong>Is the solved &quot;null space&quot; really consistent with its mathematical definition, i.e., <code>M * x = 0</code>?</strong></em></p>\n<p>Here are the behaviors of computing the null space of the same matrix but in multiple platforms, and the most important things is to verify the results.</p>\n<p><strong>As we can see, the outcomes of computing the null space of a matrix via different languages are not presented the same, but all of them meet the definition of &quot;Null Sapce&quot;, if you check the matrix product <code>M * x</code>. In this sense, the solved null space makes sense and are good enough.</strong></p>\n<hr />\n<h1>Matlab</h1>\n<pre><code>A = [1.+0.j, 0.+0.j, 0.+0.j, -0.28867513+0.5j;\n 0.+0.j, 1.+0.j, 0.+0.j, -0.28867513-0.5j;\n 0.+0.j, 0.+0.j, 1.+0.j, 0.57735027-0.5j ]\n\nx = null(A)\n</code></pre>\n<p>such that</p>\n<pre><code>x =\n\n 0.2235 - 0.3134i\n 0.1596 + 0.3502i\n -0.4151 + 0.2949i\n 0.6636 + 0.0639i\n</code></pre>\n<p>and</p>\n<pre><code>&gt;&gt; A*x\n\nans =\n\n 1.0e-15 *\n\n 0.0278 + 0.0000i\n -0.0278 + 0.1665i\n 0.0555 + 0.1110i\n</code></pre>\n<h1>R</h1>\n<pre><code>M &lt;- cbind(\n c(1, 0, 0), \n c(0, 1, 0), \n c(0, 0, 1), \n c(-0.28867513 + 0.5i, -0.28867513 - 0.5i, 0.57735027 - 0.5i)\n)\nx &lt;- Conj(MASS::Null(t(M)))\n</code></pre>\n<p>such that</p>\n<pre><code>&gt; x\n [,1]\n[1,] 0.1578535-0.35104189i\n[2,] 0.2250844+0.31222613i\n[3,] -0.3493225+0.37044977i\n[4,] 0.6632680-0.06723087i\n\n&gt; M %*% x\n [,1]\n[1,] -2.220446e-16+2.220446e-16i\n[2,] 2.775558e-17+1.110223e-16i\n[3,] 0.000000e+00-1.110223e-16i\n</code></pre>\n<h1>Python (<code>scipy=1.15.1</code>)</h1>\n<p>Given matrix <code>A</code> like below</p>\n<pre><code>from scipy.linalg import null_space\nA = np.array(\n [\n [1.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, -0.28867513 + 0.5j],\n [0.0 + 0.0j, 1.0 + 0.0j, 0.0 + 0.0j, -0.28867513 - 0.5j],\n [0.0 + 0.0j, 0.0 + 0.0j, 1.0 + 0.0j, 0.57735027 - 0.5j],\n ]\n)\n</code></pre>\n<ul>\n<li>with <code>lapack_driver=&quot;gesdd&quot;</code>, e.g.,</li>\n</ul>\n<pre><code>x = null_space(A, lapack_driver=&quot;gesdd&quot;)\n</code></pre>\n<p>such that</p>\n<pre><code>x=\n[[ 0.22039582-0.31555321j]\n [ 0.16307918+0.34864499j]\n [-0.41213333+0.29900733j]\n [ 0.6641982 +0.05731663j]]\nA@x=\n[[ 5.55111512e-17+0.00000000e+00j]\n [-4.51028104e-17+2.22044605e-16j]\n [ 5.55111512e-17+1.11022302e-16j]]\n</code></pre>\n<ul>\n<li>With <code>lapack_driver=&quot;gesvd&quot;</code>, e.g.,</li>\n</ul>\n<pre><code>x = null_space(A, lapack_driver=&quot;gesvd&quot;)\n</code></pre>\n<p>such that</p>\n<pre><code>x=\n[[ 0.19245009-3.33333334e-01j]\n [ 0.19245009+3.33333334e-01j]\n [-0.38490018+3.33333334e-01j]\n [ 0.66666667-9.12968683e-18j]]\nA@x=\n[[ 5.55111512e-17-5.55111512e-17j]\n [-1.28956617e-17+0.00000000e+00j]\n [-5.55111512e-17+0.00000000e+00j]]\n</code></pre>\n"^^ . "<p>I am translating a MATLAB script that performs spectral factorization into R using the <a href="https://cvxr.rbind.io/" rel="nofollow noreferrer">CVXR</a> package for convex optimization. I have simplified the problem to focus only on constructing the <code>Q</code> matrix while maintaining the core constraints and objective.</p>\n<h2>MATLAB Script</h2>\n<p>The following MATLAB script constructs the <code>Q</code> matrix using a convex optimization framework:</p>\n<h3>The Constraints</h3>\n<ul>\n<li>Q must be positive semi-definite.</li>\n<li>The block diagonals of Q are constrained to match the elements of R. Specifically, for every lag k (from 0 to p), the constraints ensure that the trace of each block matches the corresponding block of R.</li>\n</ul>\n<pre><code>function Q = compute_Q(n, p, Y)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%input:\n% n = number of variables\n% p = order of the true AR model\n% Y = causal part of the &quot;true&quot; matrix polynomial $S^{-1}$ (IS)\n%output:\n% Q = symmetric positive semidefinite matrix satisfying the constraints\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nR = Y;\ns = n * (p + 1);\n\ncvx_begin quiet\n variable Q(s, s) symmetric;\n maximize trace(Q(1:n, 1:n));\n subject to\n Q == semidefinite(s);\n for k = 0:p\n ind_diag = diag(ones(p + 1 - k, 1), k);\n for i = 1:n\n for j = 1:n\n ind_bl = zeros(n);\n ind_bl(i, j) = 1;\n trace(kron(ind_diag, ind_bl) * Q) == R{k + 1}(i, j);\n end\n end\n end\ncvx_end\n\nend\n\n</code></pre>\n<h3>Problem</h3>\n<p><strong>Objective</strong>: Maximize the trace of the top-left nxn block of Q, i.e., maximize trace(Q_{1:n,1:n}).</p>\n<p><strong>Constraints</strong>:</p>\n<ol>\n<li>Q &gt;= 0 (positive semidefinite constraint).</li>\n<li>trace(kron(<code>ind_diag</code>, <code>ind_bl</code>)xQ) = R_{ij}^{k}, where:</li>\n</ol>\n<ul>\n<li><code>ind_diag</code>: A diagonal matrix defining the block structure for lag k.</li>\n<li><code>ind_bl</code>: A block matrix with a single nonzero element at position\n(i,j).</li>\n</ul>\n<h2>R Translation</h2>\n<p>I translated the above MATLAB script into R using the CVXR package:</p>\n<pre><code>library(CVXR)\n\ncompute_Q &lt;- function(n, p, Y) {\n R &lt;- Y\n s &lt;- n * (p + 1)\n Q &lt;- Variable(s, s, symmetric = TRUE)\n \n # Objective: Maximize trace of the top-left block of Q\n objective &lt;- Maximize(sum(diag(Q[1:n, 1:n])))\n \n # Constraints: Q is positive semidefinite\n constraints &lt;- list(Q %&gt;&gt;% 0)\n \n # Add trace constraints for each block\n for (k in 0:p) {\n ind_diag &lt;- diag(rep(1, p + 1 - k), k)\n for (i in 1:n) {\n for (j in 1:n) {\n ind_bl &lt;- matrix(0, n, n)\n ind_bl[i, j] &lt;- 1\n constraints &lt;- c(\n constraints,\n trace(Q %*% kronecker(ind_diag, ind_bl)) == R[[k + 1]][i, j]\n )\n }\n }\n }\n \n # Solve the problem\n problem &lt;- Problem(objective, constraints)\n result &lt;- solve(problem, solver = &quot;SCS&quot;)\n \n # Return the computed Q matrix\n return(result$getValue(Q))\n}\n</code></pre>\n<h2>Inputs</h2>\n<p>The inputs for the R function are:</p>\n<pre><code>k &lt;- 9\nn &lt;- 5\np &lt;- 1\nY &lt;- list(\n matrix(c(2.1983699, 0.2066341, 0.2048484, 0.2066970, 0.2011900,\n 0.2066341, 2.1954148, 0.2043585, 0.1901186, 0.1995567,\n 0.2048484, 0.2043585, 2.2169782, 0.2075691, 0.2009464,\n 0.2066970, 0.1901186, 0.2075691, 2.2021540, 0.2096051,\n 0.2011900, 0.1995567, 0.2009464, 0.2096051, 2.1970326),\n nrow = 5, byrow = TRUE),\n matrix(c(0.1849041, 0.2060889, 0.1936582, 0.2057210, 0.2185530,\n 0.1942851, 0.2074143, 0.1904800, 0.1798709, 0.2280653,\n 0.1866000, 0.1944861, 0.1887652, 0.1946746, 0.1985805,\n 0.2231732, 0.1974313, 0.2047517, 0.1884571, 0.1967431,\n 0.2076642, 0.2123295, 0.1948372, 0.2092436, 0.1989898),\n nrow = 5, byrow = TRUE)\n)\n</code></pre>\n<h2>Error Encountered</h2>\n<p>When I run the R function:</p>\n<pre><code>Q_result &lt;- compute_Q(n, p, Y)\n</code></pre>\n<p>I get the following error:</p>\n<pre><code>Error in .local(.Object, ...) : Invalid dimensions 00\n17.\nstop(&quot;Invalid dimensions &quot;, dim)\n16.\n.local(.Object, ...)\n15.\n.nextMethod(.Object, ..., dim = intf_dim(.Object@value))\n14.\neval(call, callEnv)\n13.\neval(call, callEnv)\n12.\ncallNextMethod(.Object, ..., dim = intf_dim(.Object@value))\n11.\n.local(.Object, ...)\n10.\ninitialize(value, ...)\n9.\ninitialize(value, ...)\n8.\nnew(structure(&quot;Constant&quot;, package = &quot;CVXR&quot;), ...)\n7.\n.Constant(value = value)\n6.\nConstant(value = expr)\n5.\nas.Constant(y)\n4.\nQ %*% kronecker(ind_diag, ind_bl)\n3.\nQ %*% kronecker(ind_diag, ind_bl)\n2.\ntrace(Q %*% kronecker(ind_diag, ind_bl))\n1.\ncompute_Q(n, p, Y)\n</code></pre>\n<h2>Question</h2>\n<p>Why does the CVXR implementation fail with this &quot;Invalid dimensions&quot; error? How should the constraints be set up in R to correctly mimic the MATLAB constraints?</p>\n"^^ . "Your MATLAB result doesn’t match OP’s leading me to think OP didn’t compute their result in same way you did. They likely had a different input matrix as suggested by the other answer."^^ . . "How to Use MATLAB's RL Toolbox to Build a Reinforcement Learning Agent for Controlling PID Parameters in Track Control?"^^ . "Gazebo sim not starting because of undefined symbol from libQt5Quick.so.5"^^ . . . . . "I do not think Matlab will allow excel to run inside a compiled script. Talk to Matlab."^^ . . . . "1"^^ . . "And surely you checked that you’re running the same Python installation in VSCode and in MATLAB. Have you tried using `system(‘python Merger_CT_X_TARGET_Y.py')`?"^^ . . . . . . "null"^^ . . "1"^^ . . "0"^^ . . "geometry"^^ . . . "non-linear-regression"^^ . . "@user2587726 yes you can replace the 6 lines in your code which define `f12,f23,f13,h2,h3,h4` exactly with the 6 lines I've provided above (note they are different!) and include the additional local function in your code, and it should work the same with `fimplicit3`. The only change I've made is defining the function given to the implicit plotting differently so that it works for 3D coordinates."^^ . "0"^^ . . "1"^^ . . . . . . . . . . . . "0"^^ . . . "1"^^ . "2"^^ . . . . "1"^^ . . . . . . "Actually, boundary does not work in Matlab as I know..."^^ . . . . . . . "0"^^ . . . . . "1"^^ . . . "1"^^ . . "0"^^ . "1"^^ . . . . "Different result in Matlab and Python for StateSystem"^^ . . . . . . "I have no idea how the backslashes ended up there. I was struggling to insert code since this was my first time asking a question, so I’m pretty sure I messed something up. The code is from MATLAB. I’ve fixed it now, thank you!"^^ . "2"^^ . . . . "1"^^ . "0"^^ . . . "1"^^ . . . "Matlab fill function"^^ . "Does Matlab clear the plot before each new update or does it accumulate?"^^ . . . "8"^^ . "2"^^ . . . "0"^^ . . . "0"^^ . . . . . "Add Additional Legends for Specific Bar Colors in MATLAB Bar Chart"^^ . "0"^^ . . . "(1) Do you really need a cell array of cell arrays? It would be much easier if you stored the numbers in a numeric 2D or 3D array, or if you convert into that. (2) Is the result correct? For example, how is `33` obtained? (3) What type of array do you need the result to be? What you show is 5 separate arrays."^^ . . . . . "<p>My nightmares with discriminant analysis continue...</p>\n<p>Trying to plot the &quot;one dimensional&quot; quadratic discriminant analysis, where the discriminant is only being decided on by the x-axis. It works fine for linear (as shown in the code sample) but I can't get the quadratic (aka curved) boundaries to plot correctly. I've tried a few things (all in the code sample) to no avail.</p>\n<p>I think the issue is with what I'm passing to the implicit function, when I had problems with the 3D case this was the solution, but I just don't understand how to fix it myself.</p>\n<p>I have noticed that Qxx(1,2) = -1*Qxx(2,1), but not sure how that contributes to the issue.</p>\n<pre><code>clear\nclc\nclose all\n\n%----------------------------\nx1 = 1:0.01:3;\nr = -1 + (1+1)*rand(1,201);\nx1 = x1 + r;\n\ny1 = 1:0.01:3;\nr = -1 + (1+1)*rand(1,201);\ny1 = y1 + r;\n\nx1 = x1';\ny1 = y1';\n\nlabel1 = ones(length(y1),1);\n\nTclust1 = [label1,x1,y1];\n%----------------------------\nx2 = 7:0.01:9;\nr = -1 + (1+1)*rand(1,201);\nx2 = x2 + r;\n\ny2 = 10:0.01:12;\nr = -1 + (1+1)*rand(1,201);\ny2 = y2 + r;\n\nx2 = x2';\ny2 = y2';\n\nlabel2 = 2.*ones(length(y2),1);\n\nTclust2 = [label2,x2,y2];\n\n%----------------------------\nx3 = 15:0.01:17;\nr = -1 + (1+1)*rand(1,201);\nx3 = x3 + r;\n\ny3 = 13:0.01:15;\nr = -1 + (1+1)*rand(1,201);\ny3 = y3 + r;\n\nx3 = x3';\ny3 = y3';\n\nlabel3 = 3.*ones(length(y3),1);\n\nTclust3 = [label3,x3,y3];\n\n%----------------------------\nT = [Tclust1;Tclust2;Tclust3];\n\ndata = T(:,2:3);\nlabels = T(:,1);\n\n%LOOCV\nn = length(labels);\nhpartition = cvpartition(n,'leaveout');\n\n% figure()\noutput = zeros(n,3);\n\nfor qq = 1:n\n %training data\nidx_Train = training(hpartition,qq);\ndata_Train = data(idx_Train,1:2);\nlabels_Train = labels(idx_Train);\n\n %test data\nidx_Test = test(hpartition,qq);\ndata_Test = data(idx_Test,1:2);\nlabels_Test = labels(idx_Test);\n\n%train the model on the training data\nMdlquad = fitcdiscr(data_Train,labels_Train,'Discrimtype','quadratic');\n\n%apply to the testing data\npred_lbl = predict(Mdlquad,data_Test);\n\n(qq/n)*100\nend\n\niscorrect=output(:,1)==output(:,2);\naccuracy_full = (sum(iscorrect)/length(iscorrect))*100;\n\n%get coeffs\nK12 = Mdlquad.Coeffs(1,2).Const;\nL12 = Mdlquad.Coeffs(1,2).Linear;\nQ12 = Mdlquad.Coeffs(1,2).Quadratic;\n \nK23 = Mdlquad.Coeffs(2,3).Const;\nL23 = Mdlquad.Coeffs(2,3).Linear;\nQ23 = Mdlquad.Coeffs(2,3).Quadratic;\n\nK13 = Mdlquad.Coeffs(1,3).Const;\nL13 = Mdlquad.Coeffs(1,3).Linear;\nQ13 = Mdlquad.Coeffs(1,3).Quadratic;\n \n%plot data with boundaries -----------------------------------------------\ndata = T(:,2:3);\nlabels = T(:,1);\nxmin = min(T(:,2));\nxmax = max(T(:,2));\nymin = min(T(:,3));\nymax = max(T(:,3));\n\n%plot linear...\nfigure()\nscatter(x1,y1,'g')\nhold on\nscatter(x2,y2,'b')\nscatter(x3,y3,'r')\n\ntitle('Linear = correct')\nxlabel('variable')\nylabel('control')\n%legend('Data 1','Data 2','Data 3','Boundary 1 -&gt; 2','Boundary 2 -&gt; 3','Boundary 1 -&gt; 3','location','eastoutside') \n\n %group 1 and group 2\n f12 = @(x1,x2) K12 + L12(1)*x1 + L12(2)*x1;\n h2 = fimplicit(f12,[xmin xmax ymin ymax],'--g');\n\n %group 2 and group 3\n f23 = @(x1) K23 + L23(1)*x1+ L23(2)*x1;\n h3 = fimplicit(f23,[xmin xmax ymin ymax],'--r');\n\n %group 1 and group 3\n f13 = @(x1) K13 + L13(1)*x1+ L13(2)*x1;\n h4 = fimplicit(f13,[xmin xmax ymin ymax],'--b');\n\n%plot quadratic...\nfigure()\nscatter(x1,y1,'g')\nhold on\nscatter(x2,y2,'b')\nscatter(x3,y3,'r')\n\ntitle('Quadratic = Problematic')\nxlabel('variable')\nylabel('control')\n%legend('Data 1','Data 2','Data 3','Boundary 1 -&gt; 2','Boundary 2 -&gt; 3','Boundary 1 -&gt; 3','location','eastoutside') \n\n%group 1 and group 2\n \n f12 = @(x1) K12 + Q12(1)*x1.^2 + Q12(2)*x1.^2 + Q12(3)*x1.^2+ Q12(4)*x1.^2;\n h2 = fimplicit(f12,[xmin xmax ymin ymax],'--g');\n\n %group 2 and group 3\n f23 = @(x1) K23 + Q23(1)*x1.^2 + Q23(2)*x1.^2 + Q23(4)*x1.^2;\n h3 = fimplicit(f23,[xmin xmax ymin ymax],'--r');\n\n %group 1 and group 3\n f13 = @(x1) K13 + Q13(1)*x1.^2 + (Q13(2)+Q13(3))*x1.^2 + Q13(4)*x1.^2;\n h4 = fimplicit(f13,[xmin xmax ymin ymax],'--b');\n</code></pre>\n"^^ . "1"^^ . . . "1"^^ . "<p>You can configure your batch script to automatically elevate itself when executed, ensuring you never &quot;forget&quot; it needs sufficient privileges for its operations.</p>\n<p>Place this code as early as possible in your batch script (usually after <code>@echo off</code>, <code>setlocal</code>, and a basic argument check, so elevation isn't requested unnecessarily, such as when only displaying help syntax):</p>\n<pre class="lang-none prettyprint-override"><code>REM Check admin mode and auto-elevate if required\nopenfiles &gt; NUL 2&gt;&amp;1 || (\n REM Not elevated - perform elevation\n echo createObject^(&quot;Shell.Application&quot;^).shellExecute &quot;%~dpnx0&quot;, &quot;%*&quot;, &quot;&quot;, &quot;runas&quot;&gt;&quot;%TEMP%\\%~n0.vbs&quot;\n cscript /nologo &quot;%TEMP%\\%~n0.vbs&quot;\n goto :eof\n)\ndel /s /q &quot;%TEMP%\\%~n0.vbs&quot; &gt; NUL 2&gt;&amp;1\n</code></pre>\n<hr />\n<h3>Explanation:</h3>\n<p>The basic idea is to check if the script is already elevated using a command like <code>openfiles</code>, in &quot;mute mode&quot;, which requires elevated privileges to run. If it fails, the <code>||</code> operator triggers the auto-elevation sequence.</p>\n<ol>\n<li><p><strong>Creating VBScript Dynamically:</strong></p>\n<ul>\n<li>A temporary VBScript file is created on-the-fly. It uses <code>shellExecute</code> with the <code>runas</code> parameter to relaunch the batch script with elevation.</li>\n<li><code>%~dpnx0</code> represents the current batch script, while <code>%*</code> forwards any original command-line arguments.</li>\n</ul>\n</li>\n<li><p><strong>Executing Elevation:</strong></p>\n<ul>\n<li>The VBScript runs without elevation, but it prompts for elevation before executing the batch script.</li>\n<li>The original batch exits immediately using <code>goto :eof</code>.</li>\n</ul>\n</li>\n<li><p><strong>Returning to Elevated Script:</strong></p>\n<ul>\n<li>When the elevated batch restarts, the <code>openfiles</code> command succeeds, skipping the elevation block.</li>\n<li>The temporary VBScript file is deleted, and the batch script proceeds in the elevated environment.</li>\n</ul>\n</li>\n</ol>\n<hr />\n<h3>Limitation:</h3>\n<p>A major drawback of this method is that <code>shellExecute</code> does not allow waiting for the elevated process to finish. This means:</p>\n<ul>\n<li><strong>ShellExecute:</strong> Elevate easily but lose control over the batch script's execution.</li>\n<li><strong>Run:</strong> Control execution but cannot handle elevation automatically.</li>\n</ul>\n<h3>Workarounds:</h3>\n<ol>\n<li><p><strong>Active Waiting:</strong></p>\n<ul>\n<li>Poll the process in a loop to check if it has completed, but this risks missing short-lived processes.</li>\n</ul>\n</li>\n<li><p><strong>Advanced Win32 API:</strong></p>\n<ul>\n<li>Use more sophisticated solutions leveraging the Win32 API, which are more complex to implement in a batch script.</li>\n</ul>\n</li>\n</ol>\n<p>Unfortunately, a straightforward solution that combines automatic elevation and precise control isn't readily available in batch scripting.</p>\n"^^ . . . . "Jumped right in and posted the next question! https://stackoverflow.com/questions/79291579/one-dimensional-quadratic-discriminant-analysis-in-matlab"^^ . . . . . . . "1"^^ . . . . . . . "1"^^ . "0"^^ . . . . . . "<p>I have seen in the Mathworks official website for the <code>pixelClassificationLayer()</code> <a href="https://www.mathworks.com/help/vision/ref/nnet.cnn.layer.pixelclassificationlayer.html" rel="nofollow noreferrer">function</a> that I should update it to a custom loss function using the following code:</p>\n<pre><code>function loss = modelLoss(Y,T) \n mask = ~isnan(T);\n targets(isnan(T)) = 0;\n loss = crossentropy(Y,T,Mask=mask,NormalizationFactor=&quot;mask-included&quot;); \nend\n\nnetTrained = trainnet(images,net,@modelLoss,options); \n</code></pre>\n<p>However, I can't see any mention of the inputs 'Classes' or 'ClassWeights', which I'm currently using to define the custom pixelClassificationLayer:\n<code>pixelClassificationLayer('Classes',classNames,'ClassWeights',classWeights)</code>, where classNames is a vector containing the names of each class as a string and classWeights is a vector containing the weights of each class to balance classes when there are underrepresented classes in the training data.</p>\n<p>How can I include these parameters in my custom loss function?</p>\n"^^ . . . . "1"^^ . "Yes, I even looked at the worked examples: https://au.mathworks.com/help/stats/create-and-visualize-discriminant-analysis-classifier.html\n\n`f = @(x1,x2) K + L(1)*x1 + L(2)*x2 + Q(1,1)*x1.^2 + (Q(1,2)+Q(2,1))*x1.*x2 + Q(2,2)*x2.^2;\nh2 = fimplicit(f,[.9 7.1 0 2.5]);\nh2.Color = 'r';\nh2.LineWidth = 2;\nh2.DisplayName = 'Boundary between Versicolor & Virginica';`\n\nHowever this example is using x1 and x2, where as I only want to use x1."^^ . . . . . . . "linear-algebra"^^ . . . "<p>I have a system where a car's position is adjusted using PID control, and the car moves along a road with several measurement points (x, y coordinates). I want to improve the precision of the PID controller using a reinforcement learning (RL) agent. I referred to the MATLAB example &quot;<a href="https://ww2.mathworks.cn/help/reinforcement-learning/ug/tune-pi-controller-using-td3.html" rel="nofollow noreferrer">Tune PI Controller Using Reinforcement Learning</a>&quot; for guidance. The challenge I’m facing now is how to implement my system in Simulink. The model training should follow a similar approach to the example, but I am unsure how to structure the Simulink model to integrate the RL agent for controlling the PID parameters. Any advice or steps to help with this integration would be much appreciated!</p>\n<p>Here is the code and model I refer to and how I should modify it.<a href="https://i.sstatic.net/zrSQpG5n.png" rel="nofollow noreferrer"><br />\nReinforcement learning model of water tank system</a></p>\n<pre><code>open_system('watertankLQG');\nTs = 0.1;\nTf = 10;\ncontrolSystemTuner(&quot;ControlSystemTunerSession&quot;);\nKp_CST = 9.80199999804512;\nKi_CST = 1.00019996230706e-06;\nmdl = 'rlwatertankPIDTune';\nopen_system(mdl);\n[env,obsInfo,actInfo] = localCreatePIDEnv(mdl);\nnumObs = prod(obsInfo.Dimension);\nnumAct = prod(actInfo.Dimension);\nrng(0);\ninitialGain = single([1e-3 2]);\n\nactorNet = [\n featureInputLayer(numObs)\n fullyConnectedPILayer(initialGain,'ActOutLyr')\n ];\nactorNetGraph = layerGraph(actorNet);\nactorNet = dlnetwork(actorNetGraph);\n\n\nactor = rlContinuousDeterministicActor(actorNet,obsInfo,actInfo);\n\n\ncriticNet = localCreateCriticNetwork(numObs,numAct);\ncriticNetGraph = layerGraph(criticNet);\ncritic1 = rlQValueFunction(dlnetwork(criticNetGraph), ...\n obsInfo,actInfo,...\n ObservationInputNames='stateInLyr', ...\n ActionInputNames='actionInLyr');\n\ncritic2 = rlQValueFunction(dlnetwork(criticNetGraph), ...\n obsInfo,actInfo,...\n ObservationInputNames='stateInLyr', ...\n ActionInputNames='actionInLyr');\ncritic = [critic1 critic2];\nactorOpts = rlOptimizerOptions( ...\n LearnRate=1e-3, ...\n GradientThreshold=1);\n\ncriticOpts = rlOptimizerOptions( ...\n LearnRate=1e-3, ...\n GradientThreshold=1);\nagentOpts = rlTD3AgentOptions(...\n SampleTime=Ts,...\n MiniBatchSize=128, ...\n ExperienceBufferLength=1e6,...\n ActorOptimizerOptions=actorOpts,...\n CriticOptimizerOptions=criticOpts);\nagentOpts.TargetPolicySmoothModel.StandardDeviation = sqrt(0.1);\nagent = rlTD3Agent(actor,critic,agentOpts);\nmaxepisodes = 1000;\nmaxsteps = ceil(Tf/Ts);\ntrainOpts = rlTrainingOptions(...\n MaxEpisodes=maxepisodes, ...\n MaxStepsPerEpisode=maxsteps, ...\n ScoreAveragingWindowLength=100, ...\n Verbose=false, ...\n Plots=&quot;training-progress&quot;,...\n StopTrainingCriteria=&quot;AverageReward&quot;,...\n StopTrainingValue=-250);\n\ndoTraining = true;\n\nif doTraining\n % plot(env);\n % Train the agent.\n trainingStats = train(agent,env,trainOpts);\nelse\n % Load pretrained agent for the example.\n load(&quot;WaterTankPIDtd3.mat&quot;,&quot;agent&quot;)\nend\n\nsimOpts = rlSimulationOptions(MaxSteps=maxsteps);\nexperiences = sim(env,agent,simOpts);\nactor = getActor(agent);\nparameters = getLearnableParameters(actor);\nKi = abs(parameters{1}(1))\nKp = abs(parameters{1}(2))\nmdlTest = 'watertankLQG';\nopen_system(mdlTest); \nset_param([mdlTest '/PID Controller'],'P',num2str(Kp))\nset_param([mdlTest '/PID Controller'],'I',num2str(Ki))\nsim(mdlTest)\nrlStep = simout;\nrlCost = cost;\nrlStabilityMargin = localStabilityAnalysis(mdlTest);\n\nset_param([mdlTest '/PID Controller'],'P',num2str(Kp_CST))\nset_param([mdlTest '/PID Controller'],'I',num2str(Ki_CST))\nsim(mdlTest)\ncstStep = simout;\ncstCost = cost;\ncstStabilityMargin = localStabilityAnalysis(mdlTest);\nfigure\nplot(cstStep)\nhold on\nplot(rlStep)\ngrid on\nlegend('Control System Tuner','RL',Location=&quot;southeast&quot;)\ntitle('Step Response')\n</code></pre>\n<p>Any suggestions on how to approach this, or references to similar examples, would be greatly appreciated. Also, if anyone has any resources or insights on implementing this in Simulink, I would be thankful for your help!</p>\n"^^ . "0"^^ . . . "1"^^ . "matlab-deployment"^^ . . . . . "2"^^ . "computer-vision"^^ . "0"^^ . . . . "0"^^ . . . . . "Looks good! Can I have some more info please? Once you've made fKLQ, how have you plotted it? With fimplicit3 still?"^^ . . . "Inputting variables when running python code in MATLAB using system"^^ . . . . . . . . . "6"^^ . "Hi, Till, many thanks for your answer, and yes, this is exactly what I was expecting. I was able to implement it into the analyses code! One thing I am worried about is making it work for other maps that have angled paths so it's not exactly a simple rectangle shape."^^ . . . "Does [this](https://stackoverflow.com/questions/53742906/how-do-i-sign-the-installed-executable-of-a-compiled-matlab-program) answer your question?"^^ . . . "Very nice answer, I wonder how would this look like in comparison with a code I wrote for error propagation in [python](https://stackoverflow.com/a/79174716/16815358). Might check it out and post a question in case something does not check out :D"^^ . . "slprj is a folder created by Simulink for storing model artifacts. You can create src and include directories for your own files. include directory typically contains header files for declarations. tmwtypes.h is part of MATLAB. You do not need to include it."^^ . . "<p>Find below a solution, may be not the best one</p>\n<pre><code>[c,k]=gsort(c,'r','i');\ni=find(c(1:$-1,1)&lt;&gt;c(2:$,1));\nr=[];l=1;\nfor j=[i(1:$),size(c,1)]\n r=[r;c(j,1),sum(c(l:j,2))];\n l=j+1;\nend\n</code></pre>\n"^^ . "Matlab Convert Stuct of Nodes to Node Array"^^ . "0"^^ . "bitbucket-pipelines"^^ . . "0"^^ . "How do I track the states from a discrete state space block?"^^ . . . "0"^^ . . . "1"^^ . . . . "<p>The issue with <code>ylabel</code> being cut off usually occurs due to the figure layout and tight boundaries. You can resolve this by adjusting the axes and fig properties. You can move the <code>xlabel</code> closer to the <code>xticks</code> by adjusting its position manually.</p>\n<p>I believe this code here should solve your problems for showing <code>ylabel</code> fully and moving the <code>xlabel</code> closer to the <code>xticks</code>:</p>\n<pre><code>clear; \n% Change default axes fonts.\nset(0,'DefaultAxesFontName', 'Times New Roman')\nset(0,'DefaultAxesFontSize', 21)\n\n% Change default text fonts.\nset(0,'DefaultTextFontname', 'Times New Roman')\nset(0,'DefaultTextFontSize', 21)\n\n% Define data\nx = [100, 200, 300, 400, 500];\n\ndata = [\n 5.3, 7.3, 4.3, 3.3, 1.3;\n 4.3, 4.3, 4.3, 5.3, 10.3;\n 2.3, 7.3, 2.3, 8.3, 2.3;\n 1.3, 9.3, 8.3, 7.3, 0.3;\n 9.3, 2.3, 0.3, 2.3, 0.3;\n 6.3, 7.3, 9.3, 6.3, 7.3;\n];\n\ndatasetNames = {'A', 'B', 'C', 'D', 'E', 'F'};\n\n% Create a 3D bar chart\nfigure;\nbar3(data);\n\n% Customize the axes\nset(gca, 'XTickLabel', x, 'YTickLabel', datasetNames, 'FontSize', 21); % Set x-axis labels as number of tasks\n\n% Align labels\nxlh = xlabel('Task Count', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal', 'Rotation', -30);\nylh = ylabel('Method', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal', 'Rotation', 37);\nzlh = zlabel('Fitness', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal');\n\n% Adjust position of the xlabel to bring it closer to xticks\nxlh.Position(2) = xlh.Position(2) - 1; % Adjust the vertical position as needed\n\n% Adjust axes properties to make ylabel fully visible\nset(gca, 'Position', [0.2, 0.2, 0.6, 0.6]); % Modify axes position within the figure\nouterpos = get(gca, 'OuterPosition'); % Get current outer position\nti = get(gca, 'TightInset'); % Get tight inset for padding\nset(gca, 'Position', [outerpos(1) + ti(1), outerpos(2) + ti(2), ...\n outerpos(3) - ti(1) - ti(3), outerpos(4) - ti(2) - ti(4)]); % Adjust for tight layout\n\n% Set Z-axis limits\nzlim([0.31, max(data(:))]); % Start Z-axis at 0.31\n\n% Set view angle for better visualization\nview(45, 30);\n\n% Adjust figure size and layout\nset(gcf, 'Units', 'normalized', 'Position', [0.2, 0.2, 0.6, 0.6]);\n\n% Adjust paper size for saving\nfig = gcf;\nfig.PaperUnits = 'centimeters';\nfig.PaperPosition = [0 0 14.4 12.4]; \nfig.PaperSize = [13.4 11.5]; % width &amp; height of page\n\n% Save the figure\nprint('FST_D_S2.pdf','-dpdf','-r1200');\n</code></pre>\n<p>I may have missed something. If so, I will edit the post.</p>\n"^^ . . "0"^^ . . "App designer generated app freezes when I run the code"^^ . . "1"^^ . . "symbolic-math"^^ . . "If you are just after extracting words at the start of a line before a `=`, use `^\\s*([a-zA-Z_]\\w*)\\s*=`"^^ . "0"^^ . . "1"^^ . "0"^^ . . . . . . "2"^^ . "R: Error Running Convex Optimization With CVXR"^^ . . . . "1"^^ . "<p>I am working with a SQLite database in MATLAB and trying to insert NULL values into some fields of a table. However, MATLAB throws an error when I attempt to insert NULL. Here's an example:</p>\n<pre><code>% Define the SQLite database file name\ndbFileName = 'example.db';\n\n% Delete the database file if it exists\nif exist(dbFileName, 'file') == 2\n delete(dbFileName);\nend\n\n% Connect to the SQLite database\nconn = sqlite(dbFileName, 'create');\n\n% Create a sample table\ncreateTableQuery = [ ...\n 'CREATE TABLE example_table (' ...\n 'id INTEGER PRIMARY KEY, ' ...\n 'name TEXT, ' ...\n 'age INTEGER DEFAULT NULL' ...\n ')'];\nexec(conn, createTableQuery);\n\n% Insert data with a NULL value for the 'age' field\ninsert(conn, 'example_table', {'id', 'name', 'age'}, {1, 'John', []});\n\n% Close the database connection\nclose(conn);\n</code></pre>\n<p>When I run this code, MATLAB throws the following error:</p>\n<pre><code>Error using sqlite/insert\nInconsistent row counts for column 0 (1) and column 2 (0).\nError in test (line 22)\ninsert(conn, 'example_table', {'id', 'name', 'age'}, {1, 'John', []}); \n</code></pre>\n<p>If I replace [] with 0, the insertion works, but this is not a true NULL value.\nHow can I insert actual NULL values into a SQLite database table using MATLAB? Is there a specific syntax or workaround for this?</p>\n"^^ . . . "arrays"^^ . "3"^^ . "@ticktalk I guess you were a bit faster than me there :D"^^ . . "2"^^ . "0"^^ . . "5"^^ . . . "1"^^ . "0"^^ . "<p>I'm trying to add a C caller block in Simulink so I can add my own C functions to a Simulink Model. I have referred to a built in example in Matlab which, called 'CallCFunctionsUsingCCallerBlockExample'.</p>\n<p>This contains 3 folders, called 'include', 'slprj' and 'src'as well as some files, such as the slx file which defines the model.</p>\n<p>The main problems I have are</p>\n<ol>\n<li><p>when attempting to specify Include directories in the Simulate Target section of Model Properties, I am not sure how to make the Include folder. Presumably it's not just going to be the same one as in their example, or is it? If not, how do I know which files to put in this folder and what they need to have in? This doesn't seem to be explained in the Matlab Help section on using C caller blocks.</p>\n</li>\n<li><p>knowing which folders to have in my Matlab model directory. Do I need to include the slprj and src files, together with their contents and do these need to be the same as in their example? If not, how do I know what to put in them?</p>\n</li>\n<li><p>additionally, their C file which defines the C functions used in the model (myfunc.c) refers to 2 files at the start with the lines #myfunc.h and #tmwtypes.h. Whilst I can see where myfunc.h is in the directory and I understand what it does, which is to declare the C functions defined in myfunc.c, I can't see where tmwtypes.h is. Do I need it and again, if so, is it going to be the same as for their example and if not, how can I find out what needs to be in it?</p>\n</li>\n</ol>\n"^^ . "0"^^ . "Thanks..yes, the print statements appear in Matlab, as coded in python, so there is no problem with that. This is a really strange problem, because i dont see any reasons why this return values are not properly given back from Matlab, and this code is not complicated or advanced in any case"^^ . . "Error installing matlabengine in conda environment"^^ . . "0"^^ . . . . . . "0"^^ . . . "0"^^ . "4"^^ . . "0"^^ . "Semi-manual Doxygen callgraph"^^ . . . . "0"^^ . . "Opened `m2cpp.pl` in Vim inside of the container and it is indeed full of `^M` characters so will start thinking about a fix on monday."^^ . . "<p>I'm looking to read a large number of nodes from an OPC_UA server using</p>\n<pre><code>[val] = readValue(uaClient,read_nodes_test)\n</code></pre>\n<p>For tidiness sake, i've got my nodes stored in a struct which i've called OPC_UA_nodes. The issue is i cannot find a way to convert this struct of nodes to the node array required for the readvalue command.</p>\n<p>All documentation encourages me to use struct2cell and then cell2mat, however cell2mat does not support cell arrays containing cell arrays or objects.</p>\n<p>What is the best way to create the node array? Besides</p>\n<pre><code>nodes = [node1, node2, node3,..., node75]\n</code></pre>\n"^^ . "0"^^ . "0"^^ . . "<p>Both matlab and scipy are well-tested pieces of software and I doubt that either is giving wrong or inaccurate results. The problem is almost certainly with your input. You really need to show the code that produced those results. <strong>I don't think what you have posted here is the matrix that you have input to matlab</strong>. Actually - see below - I suspect they differ in the element at the bottom right-hand corner. EDIT: I think the version you sent to matlab had imaginary part -0.5j, whereas the version given to scipy involved just 0.j. The real part is OK.</p>\n<p>Your scipy.null_space vector correctly gives 0 when multiplied by the given matrix A; your matlab vector doesn't ... for that matrix.</p>\n<p>Given that the matrix is in reduced-row-echelon form and has rank 3, it is not that difficult to work out, to within an arbitrary unit-magnitude complex factor, a single-vector generator for the null space by hand. The ratio of elements in the two solutions is a constant (complex) number, except for the third row. This would arise if the matrices sent to scipy.null_space and to matlab differ in a single element in the bottom right-hand corner.</p>\n<p>The scipy.null_space vector is correctly normalised to 1.</p>\n<p>I doubt that either piece of software is faulty. I think you should <strong>check that you have the same matrix in both codes.</strong></p>\n<pre><code>import numpy as np\n\nA = np.array( [\n [ 1.+0.j, 0.+0.j, 0.+0.j, -0.28867513+0.5j],\n [ 0.+0.j, 1.+0.j, 0.+0.j, -0.28867513-0.5j],\n [ 0.+0.j, 0.+0.j, 1.+0.j, 0.57735027-0.j ]\n ] )\n\npython = np.array( [\n 0.24235958-0.32852474j,\n 0.16333098+0.37415192j,\n -0.40569056-0.04562718j,\n 0.70267665+0.0790286j \n ] )\n\nmatlab = np.array( [\n 0.2235 - 0.3134j,\n 0.1596 + 0.3502j,\n -0.4151 + 0.2949j,\n 0.6636 + 0.0639j \n ] )\n\nprint( 'A @ python =\\n', A @ python )\nprint( '\\n\\nA @ matlab =\\n', A @ matlab )\nprint( '\\n\\npython / matlab =\\n', python / matlab )\nprint( '\\n\\nabs(python) =\\n', np.linalg.norm( python ) )\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre><code>A @ python =\n [ 6.71328548e-09-6.37871800e-09j 6.71328548e-09+3.62128200e-09j\n -6.39980441e-09+3.54772201e-09j]\n\n\nA @ matlab =\n [-1.48162680e-05-4.63408070e-05j -1.48162680e-05-4.63408070e-05j\n -3.19703608e-02+3.31792682e-01j]\n\n\npython / matlab =\n [1.06043801+0.01707621j 1.06065285+0.01698805j 0.59761752+0.53448467j\n 1.06051995+0.01697013j]\n\n\nabs(python) =\n 1.0000000015891697\n</code></pre>\n"^^ . . . "Trying to install with pip gives another error: RuntimeError: MATLAB R2022b installation not found. Install to default location, or add <matlabroot>/bin/maca64 to DYLD_LIBRARY_PATH, where <matlabroot> is the root of a MATLAB R2022b installation.\n\neven though I have confirmed in matlab that my root is the default /Applications/MATLAB_R2022b.app"^^ . . "0"^^ . "0"^^ . "0"^^ . "0"^^ . "0"^^ . . "matlab-app-designer"^^ . . . . . . "<p>When MATLAB is running code (as it does for example in your loop), it does nothing else. UI evens are queued and not handled until the computation (code execution) stops.</p>\n<p>Instead, let your function terminate. The figure will continue to exist, and will continue to react to UI events.</p>\n<p>To interact with the COM port at regular time intervals, use <a href="https://www.mathworks.com/help/matlab/ref/timer.html" rel="nofollow noreferrer"><code>timer</code></a>. Similarly to UI events, the timer will continue running even when MATLAB is idling.</p>\n<p>Alternatively, if you need to do some long computation and still allow for user interaction, regularly issue a short <a href="https://www.mathworks.com/help/matlab/ref/pause.html" rel="nofollow noreferrer"><code>pause</code></a> so that UI events can be handled. There is also <a href="https://www.mathworks.com/help/matlab/ref/drawnow.html" rel="nofollow noreferrer"><code>drawnow</code></a>, which should allow UI events to be handled, but I have not been very successful with it in the past.</p>\n"^^ . "Nested functions don't recognize input"^^ . . "@CrisLuengo, thank you, I will pay attention to the details you have made. I try to build various study materials for my students. This option also helps me carry out individual evaluation instruments."^^ . . . . "1"^^ . . . . "Ops, you're completely right, would have been too easy.."^^ . . "I don’t know exactly how MATLAB runs Python, but if you can run it using `system` you should also be able to run it in the out-of-process mode. At least, that is what I would expect, I’d expect the two to be more or less the same thing."^^ . . . . . "I would ask Matlab the question. Matlab has lots of restrictions to maintain license control. It looks like Matlab isn't allowing Excel to run. If it did then you could run excel in a machine that does not have a Microsoft Office License. Why use Microsoft Excel when Matlab has built in Excel Methods."^^ . "well, *graphics* only insofar as it's dealing with points and lines and shape intersections perhaps. I modified the tags a little. it certainly is graph theory, and geometry."^^ . . . . . . . . . . . . . . . . "Using vpasolve to solve equation in matrix form"^^ . . "sift"^^ . . . . . "0"^^ . "1"^^ . "0"^^ . . . . "0"^^ . . . . . . "0"^^ . . "<p>I have implemented following equations both with the Matlab own ODE solvers and with a very simple finite difference scheme. The latter works properly, while the ODE code does not produce suitable solutions. What I am doing wrong? These are a set of coupled implicit differential equations.</p>\n<pre><code> % Define the range of r for the solution\n r_span = [r2, r_outlet];\n\n % Initial state vector [cm, cu, rho, p]\n y0 = [cm2, cu2, rho2, p2];\n\n % Define the ODE system\n syms cm(r) cu(r) rho(r) p(r)\n\n eq2 = cm*r*diff(rho) + rho*r*diff(cm)+cm*rho == 0;\n eq3 = diff(r*cu) == -r^2*cu*cf*rho*sqrt(cu^2+cm^2)/(rho2*cm2*b2*r2);\n eq4 = diff(p)/rho == -cu*diff(cu)-cm*diff(cm)-(cd*rho*r* (cu^2+cm^2)^1.5)/(rho2*cm2*b2*r2);\n eq5 = (gamma/(gamma-1))*diff(p/rho) == -cu*diff(cu)-cm*diff(cm);\n\n % eqns = [eq1; eq2; eq3; eq4; eq5];\n eqns = [ eq2; eq3; eq4; eq5];\n [V, S] = odeToVectorField(eqns);\n odefcn = matlabFunction(V, 'vars', {'r', 'Y'});\n\n opt = odeset('RelTol', 1e-6, 'AbsTol', 1e-8);\n\n % Solve the ODE system using ode45\n [r_sol, y_sol] = ode15s(@(r, Y) odefcn(r, Y), r_span, y0,opt);\n</code></pre>\n<p>Thanks in advance!</p>\n<p>As said before a comparison with a finite difference (FD) scheme, showed that these code cannot solve the system of equations. Also with FD it was possible to generate physically sound results. For example, conservation of mass is given for FD. In the ODE code this conservation is defined in eq1</p>\n"^^ . . "0"^^ . . "<p>I am trying to fill the area between the variable b (size 7301x1) and the minimum value of zaxis (size of zaxis is 1x1376, but I only want to use the minimum value of it) for xaxis (size 7301x1). I attempted the following code:</p>\n<pre><code>xfill = [xaxis, fliplr(xaxis)];\nyfill = [min(zaxis) * ones(size(b)), b];\nfill(xfill, yfill, 'r');\n</code></pre>\n<p>The code ran successfully, but it only filled the area for b, creating a triangle shape at the location of b and a separate horizontal line at the minimum zaxis. I would like to fill the area between the horizontal line and the plot of b. How can I achieve this?</p>\n<p>I also tried using the patch function, but I got the same result. I’m pretty sure I missed something, but I have no idea what.</p>\n<p>I tried</p>\n<pre><code>xfill = [xaxis, fliplr(xaxis)];\nyfill = [min(zaxis) * ones(size(b)), b];\npatch(xfill, yfill, 'r');\n</code></pre>\n<p>I want to fill the area between min(zaxis) and b.</p>\n"^^ . "great! consider upvoting the answer if it helped!"^^ . "Applying reweighting to a 2D Ising Model"^^ . "0"^^ . "<p>Have now fixed this. Thanks to those who replied. I shall try my best to recount all the steps below.</p>\n<p><strong>Version issues</strong></p>\n<p>Firstly, I built my own Docker image for Doxygen. I suspect the existing images on Docker Hub (<a href="https://hub.docker.com/r/corentinaltepe/doxygen" rel="nofollow noreferrer">corentinaltepe/doxygen</a>, <a href="https://hub.docker.com/r/hrektts/doxygen" rel="nofollow noreferrer">hrektts/doxygen</a>) would have worked too, but I wanted full visibility for debugging. Here is the Dockerfile that I used to build my Docker image. It runs Doxygen <code>1.9.8</code> because that's the latest version available in the Ubuntu default package repository at present.</p>\n<pre><code>FROM ubuntu:24.04\n\n# Update\nRUN apt-get update\n\n# Install\nRUN apt-get install -y vim doxygen graphviz\n\n# Working directory\nWORKDIR /doxygen/\n</code></pre>\n<p>I then generated a default Doxyfile from this version of Doxygen and changed the following settings. I think only the first two of these settings really matter, but I have included the remaining four for completeness and because they match the settings in the Doxyfile provided by <a href="https://uk.mathworks.com/matlabcentral/fileexchange/25925-using-doxygen-with-matlab" rel="nofollow noreferrer">Fabrice</a>.</p>\n<pre><code>EXTENSION_MAPPING = .m=C++\nFILTER_PATTERNS = *.m=/doxygen/m2cpp.pl\nEXTRACT_ALL = YES\nEXTRACT_PRIVATE = YES\nEXTRACT_STATIC = YES\nGENERATE_LATEX = NO\n</code></pre>\n<p>Having made these changes, I was sure that I was using a relatively recent version of Doxygen. Moreover, I knew that my Doxyfile matched the version of Doxygen. Ie: it didn't contain deprecated settings etc. In hindsite, I don't think any of these version issues were actually causing the problem, but it was good practise to resolve them.</p>\n<p><strong>EOL issues</strong></p>\n<p>Secondly, I ran the following Git commands suggested <a href="https://stackoverflow.com/questions/48692741/how-can-i-make-all-line-endings-eols-in-all-files-in-visual-studio-code-unix">here</a>.</p>\n<pre><code>git config core.autocrlf false\ngit rm --cached -r .\ngit reset --hard\n</code></pre>\n<p>Then I opened <code>m2cpp.pl</code> in VSCode and changed the End of Line (EOL) Sequence in from CRLF to LF. I had tried doing this previously but suspected Git was somehow preventing the change. On this second attempt, having run those three Git commands, the change was successful. I tested this by opening <code>m2cpp.pl</code> from Vim inside of an Ubuntu container and using <code>:e ++ff=unix</code> to show <code>^M</code> carriage return characters, as suggested <a href="https://stackoverflow.com/questions/3852868/how-to-make-vim-show-m-and-substitute-it">here</a>. Sure enough, Vim showed that there were no <code>^M</code> characters.</p>\n<p><strong>Shebang issues</strong></p>\n<p>Thirdly, I changed the first line of <code>m2cpp.pl</code> from <code>#!/usr/bin/perl.exe</code> to <code>#!/usr/bin/perl</code>. Apparently this is another Windows vs Unix thing. That first line tells the OS where to look for the Perl interpreter and Unix doesn't like the <code>.exe</code> suffix.</p>\n<p><strong>Testing locally</strong></p>\n<p>Having made these changes, I built and ran my Doxygen container locally by mounting it onto the folder that contained my Dockerfile, Doxyfile, <code>m2cpp.pl</code> and example MATLAB code in need of documentation.</p>\n<pre><code>docker build doxygen-image .\ndocker run -it --mount type=bind,src=$pwd,dst=/doxygen/ doxygen-image\n</code></pre>\n<p>Since I ran the container in interactive mode <code>-it</code>, I was able to manually run commands in it. I ran the following commands inside of the <code>/doxygen/</code> folder. The first one gives executable permission to <code>m2cpp.pl</code> and the second one runs Doxygen.</p>\n<pre><code>chmod +x m2cpp.pl\ndoxygen Doxyfile\n</code></pre>\n<p>This produced HTML files containing the expected documentation. Very good.</p>\n<p><strong>Testing in pipeline</strong></p>\n<p>Finally, I needed to run all of this automatically inside of a BitBucket Pipeline. Here is the <code>bitbucket-pipelines.yml</code> file that I wrote for that. There are no new 'discoveries' here - it just implements the same steps as when I was testing locally. The two <code>export</code> commands are needed for building Docker images inside of a BitBucket Pipeline according to <a href="https://stackoverflow.com/questions/73882715/bitbucket-pipelines-authorization-denied-by-plugin-pipelines">this thread</a>. The command for running docker differs slightly from when I was testing locally. I don't entirely understand the difference, but the output seems to be the same. This automatically generates HTML documentation inside of the Pipeline. At present, I then manually download these files from BitBucket, but I shall configure this to instead send them to the server that will host the documentation.</p>\n<pre><code>image: docker:27.4.0\n\npipelines:\n default:\n - step:\n name: Doxygen\n script:\n # Give executable permission to Doxygen MATLAB filter\n - chmod +x m2cpp.pl\n\n # Build Docker image\n - export PATH=/usr/bin:$PATH\n - export DOCKER_BUILDKIT=1\n - docker build -f Dockerfile -t doxygen-image .\n\n # Run Docker container, mount pwd, run Doxygen, remove container\n - docker run --rm -v $(pwd):/doxygen/ doxygen-image /bin/bash -c &quot;doxygen Doxyfile&quot;;\n artifacts:\n - html/**\n services:\n - docker\n</code></pre>\n"^^ . . . . . "Matlab may of fixed a bug or you need a license from Matlab. Does machine you are using have a Microsoft office license? I do not think you can run Excel from Matlab without an office license. You can run excel method using matlab features."^^ . "0"^^ . "dart-ffi"^^ . . "2"^^ . "<p>Your code goes wrong on the line</p>\n<pre><code>zx = x(yz .* circshift(yz,[0 1]) &lt;= 0);\n</code></pre>\n<p><code>yz</code> is a column vector, so <code>circshift</code>ing it by 1 in the horizontal direction doesn't do anything at all.</p>\n<p>Changing the <code>[0 1]</code> into <code>[1 0]</code> makes your code run correctly:</p>\n<pre class="lang-none prettyprint-override"><code>s =\n\n 1.0e+05 *\n\n 0.6986\n 0.0061\n -0.0000\n 2.1975\n</code></pre>\n<hr />\n<p>To make your code more robust against changes in the input data orientation, you can use <code>circshift(yz,1)</code> instead. Assuming that <code>y</code> is always a vector, this will be correct no matter if it's a column or row vector.</p>\n"^^ . . "amazon-web-services"^^ . "1"^^ . . . . "3"^^ . . "<p>I am writing down a code that first apply Butterworth (low pass filter) to a earthquake time history and then create the one sided fourier amplitude of the filtered motion and multiply it with a transfer function to obtain the modified one sided fourier spectra and in the last step inverse fast fourier transform is applied to obtain acceleration time history of the modified motion.</p>\n<p>I wrote a complete code, but in the ifft step, it doesn't work, i think it's because of that i am trying gto make ifft from one-sided amplitude spectra in a wrong way. Could you please help me about the last part ?</p>\n<pre><code>acci=load('Gilroy.txt');\n\n\n% Butterworth filtresi parametreleri\ncutoff_freq = 25; % Kesim frekansı (Hz)\nfilter_order = 4; % Filtre derecesi\n\n% Butterworth filtresi tasarımı\n[b, a] = butter(filter_order, cutoff_freq / (200 / 2), 'low');\n\n% Filtreyi ivme kaydına uygulayın\nacc = filtfilt(b, a, acci);\n\n\n\n% Earthquake Data Process\n\ndt = 0.005; % Zaman adımı\ng = 9.81; % Yerçekimi ivmesi (m/s^2)\n\nt = 0.0:dt:dt*(length(acc)-1);\n% Hız ve yer değiştirme hesaplama\nvel = cumsum(acc) * dt * g;\ndis = cumsum(vel) * dt;\n% Fourier Transform\nTs = dt; \nFs = 1 / Ts;\nACC = fft(acc, 2^nextpow2(numel(acc)));\nN = numel(acc); \nf = (0:(N-1)) / N * Fs;\nm_ACC = abs(ACC) / N;\nm_ACC = m_ACC(1:N/2+1);\nm_ACC(2:end-1) = 2 * m_ACC(2:end-1); % Tek taraflı spektrum\nf = f(1:N/2+1); % Sadece pozitif frekanslar için eksen\n\n% Zemin Parametreleri (Sert kaya üzerinde uniform, sönümsüz zemin)\nh = 3.05; % Kalınlık (m)\nVs = 320; % Vs30 (m/s)\nk = h / Vs;\n% Amplifikasyon Fonksiyonu\ny = 1 ./ abs(cos(k * 2 * pi * f)); % Amplifikasyon Fonksiyonu\n% Amplifikasyon Fonksiyonu ile çarpma\ny = y';\nN_FAS = y .* m_ACC;\n\n\n\n% Ters Fourier dönüşümü (tek taraflı spektrumdan dönüşüm)\nreconstructed_acc = ifft(N_FAS, 'symmetric'); % 'symmetric' seçeneği simetri sağlar\nreconstructed_acc= reconstructed_acc*length(reconstructed_acc);\n\n% Hız ve yer değiştirme hesaplama\nreconstructed_vel = cumsum(reconstructed_acc) * dt * g;\nreconstructed_dis = cumsum(reconstructed_vel) * dt;\n% Zaman eksenini yeniden oluşturma\nt_reconstructed = 2*(0:length(reconstructed_acc)-1) * dt;\n% Sonuçları tek bir plot altında toplama (3x3 layout, transposed)\nfigure;\nsubplot(3,3,1), plot(t, acc, '-b');\nxlabel('Time (sec)'), ylabel('Original Ground Acceleration (g)');\ntitle('Original Ground Acceleration');\ngrid on;\nsubplot(3,3,4), plot(t, vel, '-b');\nxlabel('Time (sec)'), ylabel('Velocity (m/sec)');\ntitle('Velocity');\ngrid on;\nsubplot(3,3,7), plot(t, dis, '-b');\nxlabel('Time (sec)'), ylabel('Displacement (m)');\ntitle('Displacement');\ngrid on;\nsubplot(3,3,2), plot(f, m_ACC, '-b');\nxlabel('Frequency (Hz)'), ylabel('Original Fourier Amplitude (g-s)');\ntitle('Original Fourier Amplitude (g-s)');\nxlim([0 25]);\ngrid on;\nsubplot(3,3,5), plot(f, y, '-b');\nxlabel('Frequency (Hz)'), ylabel('Amplification Function');\ntitle('Amplification Function');\nxlim([0 25]);\ngrid on;\nsubplot(3,3,8), plot(f, N_FAS, '-b');\nxlabel('Frequency (Hz)'), ylabel('Modified Fourier Amplitude (g-s)');\ntitle('Modified Fourier Amplitude (g-s)');\nxlim([0 25]);\ngrid on;\nsubplot(3,3,3), plot(t_reconstructed, reconstructed_acc, '-b');\nxlabel('Time (sec)'), ylabel('Reconstructed Ground Acceleration (g)');\ntitle('Reconstructed Ground Acceleration');\ngrid on;\nsubplot(3,3,6), plot(t_reconstructed, reconstructed_vel, '-b');\nxlabel('Time (sec)'), ylabel('Reconstructed Velocity (m/sec)');\ntitle('Reconstructed Velocity');\ngrid on;\nsubplot(3,3,9), plot(t_reconstructed, reconstructed_dis, '-b');\nxlabel('Time (sec)'), ylabel('Reconstructed Displacement (m)');\ntitle('Reconstructed Displacement');\ngrid on;\n% Plotları düzenleme\nsgtitle('Earthquake Data Analysis');\n\n\n\n\n\n\n</code></pre>\n"^^ . "2"^^ . . "1"^^ . . . "0"^^ . "With regard to removing the `^M`, I initially tried doing this in VSCode by changing the End of Line Sequence from `CRLF` to `LF`. I was suspicious that this hadn't worked, because Git didn't recognise any changes. I also tried running `dos2unix` on the filter from Powershell, but to no avail. Then I tried opening the file in Vim from inside of the container, and I was able to see and remove all `^M` characters. Surely there's a better way to do this, without me having to edit the file from inside of the container? Sorry for what I expect is a very basic question!"^^ . "<p>If you have the Image Procressing Toolbox, you can do it easily with <a href="https://www.mathworks.com/help/images/ref/im2col.html" rel="nofollow noreferrer"><code>im2col</code></a> (but the code is probably slower than the other options):</p>\n<pre><code>S = reshape(im2col(M, [N N], 'distinct'), N, N, []);\n</code></pre>\n"^^ . . . . . . . . . . . . . . . "Any decent code editor will be able to save files with UNIX-style line endings. Even some simple text editors can do this."^^ . "0"^^ . "3"^^ . . . . "medical"^^ . . . . . . . . . "<p>MLAPP files provide forward-compatibility, but don't guarantee backward-compatibility. New functionality has been added to App Designer in basically every release since it was introduced, and new functionality will inherently not work in older versions of Matlab.</p>\n<p>If you want to ensure you can use an MLAPP file in multiple different versions of Matlab, it needs to be compatible with the oldest version that you intend to use.</p>\n<p>To achieve that, you can either (1) create the app in the old version of Matlab or (2) open it in the version it was created in, and use &quot;save as&quot; to save it for compatibility with the old version. You must make sure the app does not use any functionality not supported in the old version (for example, if it uses <code>uitree</code> then you can't use it with any version prior to 2017b).</p>\n<p><a href="https://www.mathworks.com/help/matlab/creating_guis/compatibility-between-different-releases-of-app-designer.html" rel="nofollow noreferrer">https://www.mathworks.com/help/matlab/creating_guis/compatibility-between-different-releases-of-app-designer.html</a></p>\n<p><a href="https://www.matlabsolutions.com/resources/will-my-app-designer-app-be-compatible-in-previous-and-future-releases-.php" rel="nofollow noreferrer">https://www.matlabsolutions.com/resources/will-my-app-designer-app-be-compatible-in-previous-and-future-releases-.php</a></p>\n<p>As others indicated in comments, MLAPP files are effectively ZIP files with various content inside, similar to Microsoft Word DOCX files. But that doesn't really affect your problem.</p>\n"^^ . "1"^^ . . . "0"^^ . . . . "3"^^ . . . . . "What error do you get, and where?"^^ . "0"^^ . . . . "0"^^ . "I knew this must be possible but couldn't work out the order of operations. I've added this to the benchmarking in my answer since it runs faster than the other options."^^ . . "2"^^ . . "Scipy Null Space Innacurate only for Complex Values"^^ . . . . . . . . . . . "This is a graph theory problem and not a graphics problem. You should consider the problem in the form totally abstracted from graphics. The algorithms for finding paths on a graph are well-known. Basically, this is one or another form of the *backtracking* algorithm. Most likely, your graph is a general graph with loops, and it may be directed (when some routes include one-way traffic) or not."^^ . . . "<p><a href="https://i.sstatic.net/7oqvPO6e.png" rel="nofollow noreferrer">image from MATLAB to illustrate the error</a></p>\n<p>I am writing code to solve the well-known equation in matrix form, <em>F = KX</em> to solve a finite element problem. I have resorted the equation to get all the variables on the one side by adding negative eye matrix beside <code>K</code> matrix and initiating another column vector to contain <code>X</code> then <code>F</code> below. I am stuck on how to introduce the unknown variables into MATLAB and finding the proper way to solve this equation so the output can be a matrix of numerical values. Below is the code and associated error:</p>\n<pre class="lang-matlab prettyprint-override"><code>% ____ Solving Section ____ %\n% Initialize the global stiffness matrix and force vector\n% K_global is given\n% X is defined as U_global in this code\n\nK_global_2 = sym ([K_global,-1*eye(2*numNodes)]);\nU_F = sym([U_global;F_global]);\n% Define symbolic variables for U_global and F_global \neqn= K_global_2 * U_F == sym(zeros(2 * numNodes, 1));\n% Solve the system using vpasolve\nsolution = vpasolve(eqn, U_F);\n\n% Extract the solved displacements and forces\nU_global_solved = solution.U_global;\nF_global_solved = solution.F_global;\n</code></pre>\n<p>I am getting this error:</p>\n<pre><code>Error using sym.getEqnsVars&gt;checkVariables (line 98)\nSecond argument must be a vector of symbolic variables.\n</code></pre>\n<p>However, <code>U_F</code> is assigned as <code>sym</code> in the workplace as you can see in the attached image</p>\n<p>I tried to solve equation of <em>F = KX</em> in matrix form. I used <code>solve</code>, <code>vpasolve</code>, <code>linsolve</code>, but couldn't reach any results. I am excepting the out as vector column of numbers or numerical values which is <code>U_F</code>. I do not know what the source of this error is.</p>\n"^^ . . "1"^^ . . . "1"^^ . "0"^^ . . "Problem with return when calling a python function within matlab"^^ . . "<p>I have the following MATLAB code, which visualizes the difference between DCO-OFDM and m-CAP in terms of coverage area vs. QAM order. The bars represent the coverage area under various configurations, and some of the bar segments are in red and blue, indicating specific effects (e.g., LOS+NLOS).</p>\n<p>The current legend already describes the configurations (e.g., angles for m-CAP and DCO-OFDM). However, I want to add two additional legend entries specifically for the red and blue bar segments to explain their significance, as shown in the attached image.</p>\n<p>The goal is to add two additional legends under the existing ones, representing:</p>\n<ul>\n<li>Red bars: LOS+NLOS Effect on m-CAP.</li>\n<li>Blue bars: LOS+NLOS Effect on DCO-OFDM.</li>\n</ul>\n<p>Here's the image that clarifies the desired legend layout:</p>\n<p><a href="https://i.sstatic.net/cwWB47Vg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cwWB47Vg.png" alt="enter image description here" /></a></p>\n<p>May I get assistance in achieving this? Specifically:</p>\n<ul>\n<li>How can I add the red and blue legends for these bar colors without disrupting the existing legend?</li>\n<li>Is there a more efficient way to achieve this result?\nThank you in advance for your help!</li>\n</ul>\n<p>Here’s an example of my MATLAB code for creating the bar chart:</p>\n<pre><code>close all;\nclear variables;\nclc;\n\nQAM = [16, 32, 64, 128, 256, 512, 1024];\n\n%% m_CAP modulation\n\n% Beamsteering without reflection\nVEC_Beam_no_reflection_mCAP = [\n 117.5491 75.1933 53.5396 38.3105 23.0815 13.5634 6.9007; % Theta = 10\n 118.2629 76.1452 54.0155 39.0244 23.0815 13.5634 6.9007; % Theta = 30\n 118.2629 76.3831 54.0155 39.5003 22.8435 13.5634 6.9007; % Theta = 45\n 118.2629 76.6211 54.2534 39.5003 22.8435 13.5634 6.9007 % Theta = 60\n];\n\n% Beamsteering with reflection\nVEC_Beam_reflection_mCAP = [\n 121.3563 77.0970 54.7293 39.7383 22.8435 13.5634 6.9007; % Theta = 10\n 141.1065 88.7567 61.6300 42.5937 24.2713 14.5152 7.8525; % Theta = 30\n 153.7180 95.6573 67.8168 45.6871 26.6508 14.5152 8.8043; % Theta = 45\n 160.3807 100.6544 69.7204 50.4462 28.7924 16.4188 8.8043 % Theta = 60\n];\n\n%% DCO-OFDM modulation\n\n% Beamsteering without reflection\nVEC_Beam_no_reflection_OFDM = [\n 91.3742 59.7264 42.1178 28.7924 16.4188 8.8043 4.9970; % Theta = 10\n 95.4194 58.2986 34.7412 25.9369 16.4188 10.7079 4.9970; % Theta = 30\n 89.4706 59.4884 44.4973 24.7472 16.4188 8.8043 4.9970; % Theta = 45\n 83.5217 69.4825 40.2142 28.7924 16.4188 10.7079 4.9970 % Theta = 60\n];\n\n% Beamsteering with reflection\nVEC_Beam_reflection_OFDM = [\n 94.7055 61.8679 42.1178 28.7924 16.4188 8.8043 4.9970; % Theta = 10\n 113.9798 69.7204 42.1178 28.7924 16.4188 10.7079 4.9970; % Theta = 30\n 115.6454 74.9554 55.6811 28.7924 16.4188 9.7561 4.9970; % Theta = 45\n 114.4557 88.7567 50.6841 34.5033 21.1779 11.6597 4.9970 % Theta = 60\n];\n\n%% Combine Data for Bar Chart\nangles = [10, 30, 45, 60];\ndata_no_reflection = [VEC_Beam_no_reflection_mCAP; VEC_Beam_no_reflection_OFDM];\ndata_with_reflection = [VEC_Beam_reflection_mCAP; VEC_Beam_reflection_OFDM];\n\n% Generate gradient colors for m-CAP (blue) and DCO-OFDM (green)\nmCAP_blue_gradient = [linspace(0.8, 0.1, 4)', linspace(0.9, 0.2, 4)', linspace(1.0, 0.3, 4)']; % Light to dark blue\nDCO_green_gradient = [linspace(0.7, 0.1, 4)', linspace(0.9, 0.4, 4)', linspace(0.6, 0.2, 4)']; % Light to dark green\n\n% Combine colors\ncustom_colors = [mCAP_blue_gradient; DCO_green_gradient];\n\nf = figure('Position', [100, 100, 800, 600]);\n\n% Set &quot;HandleVisibility&quot; to off so these bars don't appear in legend\nb2 = bar(data_with_reflection', 'grouped','HandleVisibility','off');\nfor k = 1:length(b2)\n b2(k).FaceColor = 'flat';\n b2(k).CData = repmat([1,0,0], size(b2(k).CData, 1), 1); % [1,0,0] for red bars\nend\n\n% Plot for No Reflection\nhold on; % To plot 2nd set of bars on top\n\nb1 = bar(data_no_reflection', 'grouped');\nfor k = 1:length(b1)\n b1(k).FaceColor = 'flat';\n b1(k).CData = repmat(custom_colors(k, :), size(b1(k).CData, 1), 1);\nend\n\n% Adjust axis and grid\ngrid on;\nxticks(1:length(QAM));\nxticklabels(string(QAM));\nxlabel('QAM Order, M');\nylabel('Coverage Area (m²)');\ntitle({'Coverage Area With Reflection', 'm-CAP and DCO-OFDM'});\n\n% Update the legend\nlegend([&quot;m-CAP \\Phi_{1/2}=10°&quot;, &quot;m-CAP \\Phi_{1/2}=30°&quot;, &quot;m-CAP \\Phi_{1/2}=45°&quot;, &quot;m-CAP \\Phi_{1/2}=60°&quot;, ...\n &quot;DCO-OFDM \\Phi_{1/2}=10°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=30°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=45°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=60°&quot;], ...\n 'Location', 'Best');\n</code></pre>\n"^^ . "I have improved the description of the problem to better understand the meaning of "strips". The stripes appear as non-uniformities of noise in the image."^^ . "The other bad thing is the data format. If I were you I’d rethink how you store the data. An array has overhead (memory wise). Storing an array by itself inside a cell array doubles the overhead. Also, indexing is relatively expensive in MATLAB. Consider storing all your data in a single array (make it multi-dimensional if appropriate)."^^ . . . . "0"^^ . "2"^^ . . "4"^^ . . . "I see, thank you. Unfortunately, that doesn't resolve it. From looking at the filtered MATLAB files, it seems that the filter removes all of the function body. Ie: the filtered source code contains only function headers. This is why the callgraphs don't work."^^ . . . . "Trying to reshape/ rearrange table variables in MATLAB"^^ . . . "0"^^ . . . "1"^^ . . . "matlab-compiler"^^ . . . . "0"^^ . . . . . "2"^^ . . . . . . "1"^^ . . . . . . . . "2"^^ . "<p>I want to identify variables outside of function calls such as</p>\n<pre><code>result = someFunction(arg1, arg2) + 10\n</code></pre>\n<p>And I used pattern <code>([a-zA-Z_]\\w*)(?!\\s*\\()</code></p>\n<p>In Matlab, the result is</p>\n<pre><code>{'result'} {'someFunctio'} {'arg1'} {'arg2'}\n</code></pre>\n<p>But, I want to get</p>\n<pre><code>{'result'} {'arg1'} {'arg2'}\n</code></pre>\n<p>I'm curious why the function call is also extracted.\nAnd also why it is <code>someFunctio</code>.</p>\n"^^ . . "0"^^ . "0"^^ . . "4"^^ . . . . . "0"^^ . . "<p>I'm trying to make a flutter apllication read a 1xN matrix from a .mat file then process this data with a standalone matlab application so when I tried to acheive that the application just loses the connection at some point</p>\n<p>MATLAB function:</p>\n<pre><code>function results = singleRVAnalysis(sample, numBins)\n % SINGLE_RVANALYSIS Analyzes a single random variable sample\n %\n % Inputs:\n % sample - Array of sample data\n % numBins - Number of bins for histogram (default: 50)\n %\n % Outputs:\n % results - A structure containing PDF, CDF, mean, variance, and third moment\n\n if nargin &lt; 2\n numBins = 50; \n end\n\n edges = linspace(min(sample), max(sample), numBins + 1);\n\n counts = histcounts(sample, edges);\n binWidth = diff(edges);\n pdf = counts / (sum(counts) * binWidth(1)); \n cdf = cumsum(pdf) * binWidth(1); \n\n binCenters = edges(1:end-1) + diff(edges) / 2;\n meanValue = sum(binCenters .* pdf * binWidth(1));\n varianceValue = sum(((binCenters - meanValue).^2) .* pdf * binWidth(1));\n thirdMomentValue = sum(((binCenters - meanValue).^3) .* pdf * binWidth(1));\n\n results = struct;\n results.PDF = pdf;\n results.CDF = cdf;\n results.Mean = meanValue;\n results.Variance = varianceValue;\n results.ThirdMoment = thirdMomentValue;\n results.Edges = edges;\nend\n\n</code></pre>\n<p>Flutter Code:</p>\n<pre><code>import 'dart:ffi';\nimport 'dart:io';\nimport 'package:ffi/ffi.dart';\nimport 'package:flutter_bloc/flutter_bloc.dart';\nimport 'package:file_picker/file_picker.dart';\n\nconst String dllPath = 'lib\\\\SingleRVAnalysis\\\\SingleRVAnalysisLib.dll';\n\nfinal DynamicLibrary singleRVAnalysisLib = DynamicLibrary.open(dllPath);\n\nfinal class Results extends Struct {\n external Pointer&lt;Double&gt; pdf;\n external Pointer&lt;Double&gt; cdf;\n @Double()\n external double mean;\n @Double()\n external double variance;\n @Double()\n external double thirdMoment;\n external Pointer&lt;Double&gt; edges;\n @Int32()\n external int binCount;\n}\n\ntypedef SingleRVAnalysisNative = Results Function(\n Pointer&lt;Double&gt;, Int32, Int32);\ntypedef SingleRVAnalysisDart = Results Function(Pointer&lt;Double&gt;, int, int);\n\nfinal singleRVAnalysis = singleRVAnalysisLib.lookupFunction&lt;\n SingleRVAnalysisNative, SingleRVAnalysisDart&gt;('mlxSingleRVAnalysis');\n\nenum FileProcessStatus { idle, processing, completed, failed }\n\nclass FileProcessCubit extends Cubit&lt;Map&lt;String, dynamic&gt;&gt; {\n FileProcessCubit() : super({'status': FileProcessStatus.idle, 'file': null});\n\n void pickFile() async {\n try {\n final result = await FilePicker.platform.pickFiles();\n\n if (result != null &amp;&amp; result.files.single.path != null) {\n emit({\n 'status': FileProcessStatus.processing,\n 'file': result.files.single,\n });\n await processFile(result.files.single);\n } else {\n emit({\n 'status': FileProcessStatus.failed,\n 'error': 'No file selected',\n });\n }\n } catch (e) {\n emit({\n 'status': FileProcessStatus.failed,\n 'error': 'File picking error: $e',\n });\n }\n }\n\n Future&lt;void&gt; processFile(PlatformFile file) async {\n final filePath = file.path;\n\n if (filePath == null) {\n emit({\n 'status': FileProcessStatus.failed,\n 'error': 'No file path available',\n });\n return;\n }\n\n try {\n final content = await File(filePath).readAsBytes();\n\n if (content.isEmpty) {\n throw Exception('The file is empty.');\n }\n\n final List&lt;double&gt; sample = content\n .toString()\n .replaceAll(RegExp(r'[^\\d\\.\\-eE, ]'), '')\n .split(RegExp(r'[,\\s]+'))\n .where((e) =&gt; e.isNotEmpty)\n .map((e) =&gt; double.tryParse(e) ?? 0.0)\n .toList();\n\n if (sample.isEmpty) {\n throw Exception('Sample array is empty.');\n }\n\n const int numBins = 50;\n final Pointer&lt;Double&gt; samplePointer = listToPointerDouble(sample);\n final result = singleRVAnalysis(samplePointer, sample.length, numBins);\n\n try {\n final pdf = result.pdf.asTypedList(numBins).toList();\n final cdf = result.cdf.asTypedList(numBins).toList();\n final mean = result.mean;\n final variance = result.variance;\n final thirdMoment = result.thirdMoment;\n\n emit({\n 'status': FileProcessStatus.completed,\n 'mean': mean,\n 'variance': variance,\n 'thirdMoment': thirdMoment,\n 'pdf': pdf,\n 'cdf': cdf,\n });\n } catch (e) {\n emit({\n 'status': FileProcessStatus.failed,\n 'error': 'Error during DLL processing: $e',\n });\n } finally {\n calloc.free(samplePointer);\n }\n } catch (e) {\n emit({\n 'status': FileProcessStatus.failed,\n 'error': 'Processing failed: $e',\n });\n }\n }\n\n void reset() {\n emit({'status': FileProcessStatus.idle, 'file': null});\n }\n}\n\nPointer&lt;Double&gt; listToPointerDouble(List&lt;double&gt; sample) {\n final Pointer&lt;Double&gt; pointer =\n calloc.allocate&lt;Double&gt;(sample.length, alignment: 8);\n\n for (int i = 0; i &lt; sample.length; i++) {\n pointer[i] = sample[i];\n }\n\n return pointer;\n}\n\n</code></pre>\n<p>It should allocate the sample pointer then pass it to the function to return the results but It crashes at some point in allocating the samplePointer</p>\n"^^ . "filesystems"^^ . "1"^^ . . "<p>The ylabel gets half shown in the graph. Help me solving the problem, such that the ylabel is shown fully. Also, it would be better if the xlabel is moved near to the xtick. The code is written in Matlab. I would request to provide a solution in Matlab itself. Thanks in advance.\nBelow is the Matlab code:</p>\n<pre><code>clear; \n% Change default axes fonts.\nset(0,'DefaultAxesFontName', 'Times New Roman')\nset(0,'DefaultAxesFontSize', 21)\n\n% Change default text fonts.\nset(0,'DefaultTextFontname', 'Times New Roman')\nset(0,'DefaultTextFontSize', 21)\n\n% Define data\nx = [100, 200, 300, 400, 500];\n\ndata = [\n 5.3, 7.3, 4.3, 3.3, 1.3;\n 4.3, 4.3, 4.3, 5.3, 10.3;\n 2.3, 7.3, 2.3, 8.3, 2.3;\n 1.3, 9.3, 8.3, 7.3, 0.3;\n 9.3, 2.3, 0.3, 2.3, 0.3;\n 6.3, 7.3, 9.3, 6.3, 7.3;\n];\n\ndatasetNames = {'A', 'B', 'C', 'D', 'E', 'F'};\n\n% Create a 3D bar chart\nfigure;\nbar3(data);\n% Customize the axes \nset(gca, 'XTickLabel', x, 'YTickLabel', datasetNames, 'FontSize', 21); % Set x-axis labels as number of tasks\n\n% Align labels\nxlh = xlabel('Task Count', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal', 'Rotation', -30);\nylh = ylabel('Method', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal', 'Rotation', 37);\nzlh = zlabel('Fitness', 'FontSize', 21, 'FontName', 'Times New Roman', 'FontWeight', 'normal');\n\n% Set Z-axis limits\nzlim([0.31, max(data(:))]); % Start Z-axis at 0.0018\n\n% Set view angle for better visualization\nview(45, 30);\n\n% Adjust figure size and layout\nset(gcf, 'Units', 'normalized', 'Position', [0.2, 0.2, 0.6, 0.6]);\n\n% Adjust paper size for saving\nfig = gcf;\nfig.PaperUnits = 'centimeters';\nfig.PaperPosition = [0 0 14.4 12.4]; \nfig.PaperSize = [13.4 11.5]; % width &amp; height of page\n\n% Save the figure\nprint('FST_D_S2.pdf','-dpdf','-r1200');\n\n</code></pre>\n"^^ . . "1"^^ . . . . "<p>You can choose <code>'UseExcel',false</code> but then you have a different issue with the formula not evaluating unless you manually edit the cell to confirm its contents.</p>\n<p>It looks like this is primarily an issue in setting the <code>Value</code> or <code>Formula</code> properties of a range, which MATLAB is likely doing under the hood via the COM interface with <code>'UseExcel',true</code>.</p>\n<p>For whatever reason, Excel is automatically adding the @ symbol for &quot;implicit intersection&quot; because it's trying to &quot;cleverly&quot; handle the fact that <code>EXACT</code> can return an array output.</p>\n<p>To get around this you might have to set the <code>.Formula2</code> data instead. I'll leave the details of the COM interface calls to you, but broadly you've got something like this to get the sheet reference to an open workbook (would work on a closed workbook with different calls):</p>\n<pre><code>Excel = actxGetRunningServer('Excel.Application');\nWorkbook = Excel.Workbooks.Item(1);\nSheet = Workbook.Sheets.Item(1);\n</code></pre>\n<p>Then for some cell <code>c</code>:</p>\n<pre><code>Sheet.Range('A1:D1').Formula2 = c;\n</code></pre>\n<p>You could also write some functions to generate the <code>'A1:D1'</code> string for you based on the upper-left cell and the size of <code>c</code>,</p>\n"^^ . "wide-format-data"^^ . . . "0"^^ . "pid"^^ . . . . . "bar-chart"^^ . . "0"^^ . . . . . "1"^^ . "1"^^ . "0"^^ . "2"^^ . . . . . "nested"^^ . "MATLAB Runtime 2024b TypeInitializationException in COM-registered Windows Forms Control Library"^^ . "2"^^ . . "opc-ua"^^ . . . "Also, see here for in-process Python execution: https://www.mathworks.com/help/matlab/matlab_external/call-user-defined-custom-module.html#buuz303 -- and here for out-of-process Python execution: https://www.mathworks.com/help/matlab/matlab_external/reload-python-interpreter.html"^^ . . . "Yes, that will work. Good solution!"^^ . . . "2"^^ . "`([a-zA-Z]\\w*)\\>(?!\\s*\\()` This one works\nSorry for unclear question....\nThe purpose was extract all variable names including left-hand side of equal"^^ . . "ffi"^^ . . . . "1"^^ . . "0"^^ . . "0"^^ . "How to calculate magnitude for a filter to specific dB level?"^^ . . . "Dart FFI with MATLAB"^^ . . "0"^^ . "@CrisLuengo yes, probably that is the reason. My point was that, we don't need to force all solved null space the same, but checking it meets the definition of "null space" should be sufficient."^^ . . . . . . . "1"^^ . "1"^^ . . "<p>I solved the problem by a simple restart of matlab, I was not aware of this apparently simple &quot;issue&quot;. So when changing the python code one has to restart matlab to execute the updated python code. Maybe an other solution would be to somehow terminate and reboot the python environment in matlab.</p>\n"^^ . . "<p>Assuming we have a matrix M of size N^2 x N^2 elements (e.g., 9x9), what's the fastest way to split it into say 3x3 segments (each with 3x3 elements).</p>\n<p>One way that comes to mind is the following:</p>\n<pre><code>M = magic(9);\nN = 3; \n\nm = mat2cell(M, N * ones(1, size(M, 1) / N), ...\n N * ones(1, size(M, 2) / N));\n</code></pre>\n<p>I, however, do not prefer the use of cells. I was curious if there is a way to split the matrix and store the segments in the form of a 3D matrix using a column-major indexing for the segments (e.g., the first segment m{1} becomes m(:, :, 1) and the second segment m{2} becomes m(:, :, 2), and so on).</p>\n"^^ . . . "0"^^ . . . "matlab-spm"^^ . . . . . "<p>Here's a minimal example of my problem:</p>\n<pre><code>innerFunc([2, 4, 5]) % works fine\nouterFunc(innerFunc, [2, 4, 5]) % doesn't work\n\nfunction out = innerFunc(my_vec) \n my_vec % not recogniced when called from outerFunc\n out = -1;\nend\n\nfunction out = outerFunc(func, my_vec) \n out = func(my_vec);\nend\n\n</code></pre>\n<p>This is the output of the code:</p>\n<pre><code>\nmy_vec =\n\n 2 4 5\n\n\nans =\n\n -1\n\nNot enough input arguments.\n\nError in nested_funcs_bug&gt;innerFunc (line 5)\n my_vec % not recogniced when called from outerFunc\n\nError in nested_funcs_bug (line 2)\nouterFunc(innerFunc, [2, 4, 5]) % doesn't work\n\n&gt;&gt; \n</code></pre>\n<p>I don't know why the eror in line 2?</p>\n<p>Especially since &quot;innerFunc&quot; usually works and I pass it an input in the outerFunc function.</p>\n"^^ . "0"^^ . "<p>I have this Matlab code that create a sinusoidal fit from a set of data</p>\n<pre><code>data = importdata('analisipicco.txt') ; \nx = data(:,1) ; y = data(:,2) ; \nyu = max(y);\nyl = min(y);\nyr = (yu-yl); % Range of ‘y’\nyz = y-yu+(yr/2);\nzx = x(yz .* circshift(yz,1) &lt;= 0); % Find zero-crossings\nper = 2*mean(diff(zx)); % Estimate period\nym = mean(y); % Estimate offset\n\nfit = @(b,x) b(1).*(sin(2*pi*x./b(2) + 2*pi/b(3))) + b(4); % Function to fit\nfcn = @(b) sum((fit(b,x) - y).^2); % Least-Squares cost function\ns = fminsearch(fcn, [yr; per; -1; ym]); % Minimise Least-Squares\n\nxp = linspace(min(x),max(x));\n\nxlabel(&quot;passi motore&quot;);\nylabel(&quot;intensità (u.a.)&quot;);\nfigure(1)\nplot(x,y,'o', xp,fit(s,xp), 'r')\ngrid\n</code></pre>\n<p>Where the elements of output parameter vector, s ( b in the function ) are:</p>\n<p>s(1): sine wave amplitude (in units of y)</p>\n<p>s(2): period (in units of x)</p>\n<p>s(3): phase (phase is s(2)/(2*s(3)) in units of x)</p>\n<p>s(4): offset (in units of y)</p>\n<p>For acknowledge this is my data set:</p>\n<pre><code>-200 183966\n-192 189734\n-184 195724\n-176 201663\n-168 207557\n-160 213278\n-152 219000\n-144 224677\n-136 229500\n-128 236024\n-120 241968\n-112 247787\n-104 252963\n-96 257491\n-88 261967\n-80 267373\n-72 273494\n-64 278599\n-56 281476\n-48 282610\n-40 283097\n-32 283839\n-24 284971\n-16 286169\n-8 287164\n0 287968\n8 288561\n16 288626\n24 288107\n32 286967\n40 285132\n48 282828\n56 279847\n64 276296\n72 272299\n80 268080\n88 263564\n96 258926\n104 254052\n112 248894\n120 243694\n128 238177\n136 232665\n144 227143\n152 221959\n160 216874\n168 211678\n176 206540\n184 201537\n192 196748\n200 192091\n</code></pre>\n<p>The program works out fine, but my question is about finding the errors on the parameters and the covariance as well, I could implement the matrix method and finding the covariance matrix but I don't know how to write as a code.<br />\nI'm new to Matlab so I want to ask if there was some function that calculate the errors as well.\nThank you in advance :))</p>\n"^^ . . "matlab-figure"^^ . "1"^^ . "Trying to obtain coefficient matrix of Bspline matrix then obtaining its quasi-diagonal matrix?"^^ . . . . "0"^^ . "woah, that works! how?"^^ . "sum"^^ . . "curve-fitting"^^ . "1"^^ . "3"^^ . . "<p>The goal is to segment the major paths by turns in a shortest path of a virtual reality map to know how much to score a person's navigation trajectory (blue line in image) based on how far they walked on the shortest path.</p>\n<p>The problem right now is the algorithm function is plotting the 1st path segment good but the next segment plotted is the same sized bounding box but on the next x,y line segment position of the shortest path (right next to the first x, y line segment - in <em>idealPath</em> variable)\n<a href="https://i.sstatic.net/65QPdLEB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/65QPdLEB.png" alt="1st path segment good" /></a>\n<a href="https://i.sstatic.net/j162HlFd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/j162HlFd.png" alt="2nd path segment issue" /></a></p>\n<p>How can I fix my current code to detect the next path segment and plot the next bounding segmentation box (in orange)? <em>idealPath</em> which is the shortest path plotted in green in this case is 94666x2 where column 1 is the x position and 2 is the y position to plot as line segments to form the green path in the image.</p>\n<p>Current code block:</p>\n<pre><code>function plotSegmentedCheckpoints(trajectory_raw, idealPath, checkpointInfo)\n % Clear and hold the plot\n cla;\n hold on;\n \n % Plot ideal path in green\n plot(idealPath(:,1), idealPath(:,2), 'g.', 'MarkerSize', 5, 'DisplayName', 'Ideal Path');\n \n % Plot trajectory in blue\n scatter(trajectory_raw(:,1), trajectory_raw(:,2), 15, 'b', 'filled', 'DisplayName', 'Trajectory');\n\n % Get path segments\n [segmentIndices, numSegments] = findPathSegments(idealPath);\n \n % Initialize checkpoint storage\n checkpoint_bounds = zeros(numSegments, 4); % [x1, x2, y1, y2]\n reached = false(numSegments, 1);\n \n % Constants\n BOX_WIDTH = 86; % Width of checkpoint boxes\n \n % Process each segment\n for i = 1:numSegments\n % Get current segment\n startIdx = segmentIndices(i);\n endIdx = segmentIndices(i+1);\n segmentPoints = idealPath(startIdx:endIdx, :);\n \n % Calculate segment bounds\n [bounds, orientation] = calculateSegmentBounds(segmentPoints, BOX_WIDTH);\n checkpoint_bounds(i,:) = bounds;\n \n % Check if trajectory reaches this checkpoint\n reached(i) = checkCheckpointReached(trajectory_raw, bounds);\n \n % Draw checkpoint box\n drawCheckpointBox(bounds, reached(i), i);\n \n % Draw direction arrow to next checkpoint if not last segment\n if i &lt; numSegments\n drawDirectionArrow(bounds, idealPath(segmentIndices(i+1),:));\n end\n end\n \n % Calculate and display score\n score = calculateScore(reached, numSegments);\n \n % Configure plot\n configureplot();\n \n % Update title with progress\n title(sprintf('Checkpoint Progress: (%d/%d)\\nScore: %.2f', ...\n sum(reached), numSegments, score));\n \n % Store checkpoint information\n checkpointInfo.bounds = checkpoint_bounds;\n checkpointInfo.reached = reached;\n checkpointInfo.score = score;\nend\n\n% Function to find path segments based on direction changes\nfunction [segmentIndices, numSegments] = findPathSegments(idealPath)\n % Calculate path directions\n vectors = diff(idealPath);\n angles = atan2(vectors(:,2), vectors(:,1));\n \n % Find significant direction changes (&gt; 30 degrees)\n angleChanges = [true; abs(diff(angles)) &gt; pi/6];\n \n % Combine consecutive changes that are very close\n MIN_SEGMENT_LENGTH = 50;\n for i = 2:length(angleChanges)-1\n if angleChanges(i) &amp;&amp; angleChanges(i+1) &amp;&amp; ...\n (i - find(angleChanges(1:i-1), 1, 'last') &lt; MIN_SEGMENT_LENGTH)\n angleChanges(i) = false;\n end\n end\n \n % Get indices where direction changes significantly\n segmentIndices = find(angleChanges);\n \n % Ensure first and last points are included\n if segmentIndices(1) ~= 1\n segmentIndices = [1; segmentIndices];\n end\n if segmentIndices(end) ~= size(idealPath,1)\n segmentIndices = [segmentIndices; size(idealPath,1)];\n end\n \n % Number of segments\n numSegments = length(segmentIndices) - 1;\nend\n\n% Function to calculate bounds for a segment\nfunction [bounds, orientation] = calculateSegmentBounds(segmentPoints, BOX_WIDTH)\n % Determine if segment is more vertical or horizontal\n endpoint_diff = diff(segmentPoints([1 end],:));\n is_vertical = abs(endpoint_diff(2)) &gt; abs(endpoint_diff(1));\n \n if is_vertical\n % Vertical segment\n x_center = mean(segmentPoints(:,1));\n y_range = [min(segmentPoints(:,2)), max(segmentPoints(:,2))];\n \n bounds = [\n x_center , % x1\n x_center + BOX_WIDTH, % x2\n y_range(1), % y1\n y_range(2) % y2\n ];\n orientation = 'vertical';\n else\n % Horizontal segment\n y_center = mean(segmentPoints(:,2));\n x_range = [min(segmentPoints(:,1)), max(segmentPoints(:,1))];\n \n bounds = [\n x_range(1), % x1\n x_range(2), % x2\n y_center , % y1\n y_center + BOX_WIDTH % y2\n ];\n orientation = 'horizontal';\n end\nend\n\n% Function to check if trajectory reaches checkpoint\nfunction reached = checkCheckpointReached(trajectory, bounds)\n in_x = trajectory(:,1) &gt;= bounds(1) &amp; trajectory(:,1) &lt;= bounds(2);\n in_y = trajectory(:,2) &gt;= bounds(3) &amp; trajectory(:,2) &lt;= bounds(4);\n reached = any(in_x &amp; in_y);\nend\n\n% Function to draw checkpoint box\nfunction drawCheckpointBox(bounds, is_reached, checkpoint_number)\n x = [bounds(1), bounds(2), bounds(2), bounds(1), bounds(1)];\n y = [bounds(3), bounds(3), bounds(4), bounds(4), bounds(3)];\n \n if is_reached\n fill(x(1:4), y(1:4), [0.8 1 0.8], 'FaceAlpha', 0.3, 'EdgeColor', 'k', 'LineWidth', 1);\n else\n fill(x(1:4), y(1:4), [1 0.8 0.8], 'FaceAlpha', 0.3, 'EdgeColor', 'k', 'LineWidth', 1);\n end\n \n % Add checkpoint number\n text(mean([bounds(1), bounds(2)]), mean([bounds(3), bounds(4)]), ...\n num2str(checkpoint_number), 'HorizontalAlignment', 'center', ...\n 'VerticalAlignment', 'middle', 'FontSize', 12, ...\n 'FontWeight', 'bold', 'Color', 'k');\nend\n\n% Function to draw direction arrow\nfunction drawDirectionArrow(current_bounds, next_point)\n % Calculate arrow start point (center of current box)\n arrow_start = [\n mean([current_bounds(1), current_bounds(2)]), \n mean([current_bounds(3), current_bounds(4)])\n ];\n \n % Calculate direction to next checkpoint\n dir_vec = next_point - arrow_start;\n dir_vec = dir_vec / norm(dir_vec) * 50; % Fixed length arrows\n \n % Draw arrow\n quiver(arrow_start(1), arrow_start(2), dir_vec(1), dir_vec(2), 0, ...\n 'Color', [1 0.5 0], 'LineWidth', 2, 'MaxHeadSize', 0.5);\nend\n\n% Function to calculate score\nfunction score = calculateScore(reached, numSegments)\n weights = linspace(1, 2, numSegments);\n score = sum(reached .* weights') / sum(weights);\nend\n\n% Function to configure plot\nfunction configureplot()\n grid on;\n axis equal;\n set(gca, 'YDir', 'reverse');\n xlabel('X Position (cm)');\n ylabel('Y Position (cm)');\n legend('Location', 'northwest');\n xlim([0 600]);\n ylim([0 600]);\nend\n</code></pre>\n<p>Edit:\nWith Till's suggestion, I was able to implement it and plot the segmented paths onto the figure.</p>\n<p><a href="https://i.sstatic.net/jtITUKGF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jtITUKGF.png" alt="Working output" /></a></p>\n"^^ . . . "1"^^ . "0"^^ . "covariance-matrix"^^ . . . "interpolation"^^ . . "<p>I have a MATLAB application that performs regression using LinearModel.stepwise. I translated the regression process into Python and tried pycaret, OLS, and RLM for regression. However, I noticed differences in the results compared to MATLAB. To ensure consistency, I want to use the MATLAB regression model within my Python application.</p>\n<p>Locally, I can call MATLAB code from Python using the MATLAB Engine API for Python.</p>\n<p>However, my long-term goal is to deploy this application on AWS. Since I have no prior experience with AWS, I am trying to understand the best approach.</p>\n<p>My questions:</p>\n<ol>\n<li>Do the solutions mentioned in <a href="https://www.mathworks.com/help/cloudcenter/ug/run-matlab-on-amazon-web-services.html" rel="nofollow noreferrer">Run MATLAB on AWS</a> and <a href="https://stackoverflow.com/questions/63142358/execute-matlab-on-aws?rq=3">MATLAB in AWS</a> involve running a full MATLAB instance in AWS?</li>\n<li>Is there an API or service that allows calling specific MATLAB functions and returning results without running a full MATLAB instance in AWS?\nAny guidance on configuring MATLAB in AWS for this use case would be greatly appreciated.</li>\n</ol>\n"^^ . . "0"^^ . . . "0"^^ . . "<p>You can generate a mesh for x-y points in the bounding box of your polygon, then make points outside the polygon equal to <code>NaN</code> using <code>inpolygon</code>, then calculate the surface based on all points, which will be <code>NaN</code> for points outside the polygon.</p>\n<p>From your example:</p>\n<pre><code>% Input function and polygon for example\nf =@(x,y) x.*y;\n% Polygon is [x, y] points\np = [0 0\n 1 0\n 2 2\n 0 1];\n\n% Generate x-y mesh for bounding box of polygon\nn = 1000; % number of points in each direction\nx = linspace( min(p(:,1)), max(p(:,1)), n ); % grid points for x\ny = linspace( min(p(:,2)), max(p(:,2)), n ); % grid points for y\n[x,y] = meshgrid( x, y ); % all x-y combinations for grid\n\nb = inpolygon( x, y, p(:,1), p(:,2) ); % check which points are in the polygon\nx(~b) = NaN; % make points outside the polygon equal to NaN\ny(~b) = NaN; % so that f(x,y) is also NaN\n\n% Plot the patch of the original polygon and the surface f(x,y)\nfigure(1); clf; hold on; grid on;\npatch( p(:,1), p(:,2), 'k', 'displayname', 'x-y poly' );\nsurf( x, y, f(x,y), 'displayname', 'f(x,y) in poly', 'edgecolor', 'flat' );\nlegend( 'show', 'location', 'north' ); view( 6, 25 ); colormap( 'jet' );\n</code></pre>\n<p>Example output:</p>\n<p><a href="https://i.sstatic.net/82g33rmT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/82g33rmT.png" alt="surface with bounding polyogn" /></a></p>\n"^^ . . . "Which version of doxygen are you using? Did you have a look at `FILTER_SOURCE_FILES`?"^^ . . . . "<p>You could split out a table subset for each unique value of <code>Channel</code>, prefix the measurement columns with the corresponding channel name, and then join the table subsets back together on the ID. Here is an example with similar data to in your question, please see the code comments for more details:</p>\n<pre><code>% Set up example data table\nID = [1;1;2;2];\nChannel = {'F7';'F8';'F7';'F8'};\nAlpha = [9;8;7;6];\nBeta = [1;2;3;4];\nGamma = [0.1;0.2;0.3;0.4];\n\nT = table( ID, Channel, Alpha, Beta, Gamma );\n\n% Get the unique channels which need unstacking\nchannels = unique( T.Channel );\nfor n = 1:numel(channels)\n % For each channel, get the table subset\n temp = T( strcmp( T.Channel, channels{n} ), : );\n % Remove the redundant Channel column and prefix all non-ID columns\n % with the channel name for this subset\n temp.Channel = [];\n temp.Properties.VariableNames(2:end) = strcat( channels{n}, '_', temp.Properties.VariableNames(2:end) );\n % If this is the first iteration then just assign the temp table to the\n % wide output. Otherwise perform a join on the ID\n if n == 1\n Twide = temp;\n else\n Twide = outerjoin( Twide, temp, 'Keys', 'ID', 'MergeKeys', true );\n end\nend\n</code></pre>\n<p>Output:</p>\n<pre><code>Twide =\n 2×7 table\n ID F7_Alpha F7_Beta F7_Gamma F8_Alpha F8_Beta F8_Gamma\n __ ________ _______ ________ ________ _______ ________\n\n 1 9 1 0.1 8 2 0.2 \n 2 7 3 0.3 6 4 0.4 \n</code></pre>\n"^^ . "The `^M` can be removed (when using vi) by setting the file to binary mode (`:set bin`) and removing the `^M` characters afterwards or use the command `dos2unix`"^^ . . . "The worst part of your code is the line `sum=[sum sumi]`, which creates a new array and copies the data into it. You should never do that inside a loop. Read about preallocation: https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html"^^ . . . "0"^^ . . . . . . . . "0"^^ . "The second option is what I need, and it works. Thank you very much"^^ . . . "0"^^ . . . "1"^^ . . "How to create Simulink block e^2s"^^ . . "1"^^ . . . "Integrating MATLAB Regression into a Python Application on AWS Cloud"^^ . . . . . "0"^^ . . "Update the content of a MatLab generated executable"^^ . . "0"^^ . . "What version of setuptools are you using? Usually you can ignore deprecationWarnings, but maybe in your case that's causing the installation to fail."^^ . . . "0"^^ . . . . . . . "0"^^ . . . . . . . . "0"^^ . "<p>I have this part of my MATLAB script where im trying to run a python code:</p>\n<pre class="lang-matlab prettyprint-override"><code>%%% MATLAB %%%\nsystem(sprintf('python &quot;%s&quot; &quot;%s&quot; &quot;%s&quot;', 'Merge_CT_MRI_targets.py', num2str(OriginalPatients(index_target)), num2str(target_list(index_target))));\ndisp('test1')\n</code></pre>\n<p>This is the python script:</p>\n<pre class="lang-py prettyprint-override"><code>### PYTHON ###\nimport itk\nimport numpy as np\nimport os\nimport time\n\nMRI_target = itk.imread(&quot;MRI_&quot;+target+&quot;_&quot;+originalPatient+&quot;.nii&quot;, itk.F)\n</code></pre>\n<p>However, it looks like the variables aren't being properly called in the python script:</p>\n<pre class="lang-none prettyprint-override"><code>% matlab command window %\nTraceback (most recent call last): \n File &quot;Merge_CT_MRI_targets.py&quot;, line 23, in &lt;module&gt; \n MRI_target = itk.imread(&quot;MRI_&quot;+target+&quot;_&quot;+originalPatient+&quot;.nii&quot;, itk.F) \n ^^^^^^ \nNameError: name 'target' is not defined \n</code></pre>\n<p>Any help is appreciated. I previously tried using pyrunfile but it also brings an error.</p>\n"^^ . . . "10"^^ . "So what is wrong with your last approach? You get the Dot files, then you add `\\dotfile` commands as you suggest for the manual approach. Is that really too much to do manually? How many functions do you have?"^^ . . "<p>I am trying to translate the following MATLAB code to Python. In MATLAB, the code dynamically updates a single plot for multiple iterations (n = 1:100), and each update displays the interpolation alongside the original function.</p>\n<pre><code>for n = 1:100\n [err, t, f, x, p] = intlag(n);\n plot(x, sin(x), '-r', x, p, '-b'); % 1./(5*x.*x+1)\n axis([-1 1 -2 2])\n legend('fonction', 'interpolant')\n title(['t = ', num2str(n)])\n drawnow\nend\n</code></pre>\n<p><a href="https://i.sstatic.net/Kn3aK1vG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Kn3aK1vG.png" alt="enter image description here" /></a></p>\n<p>I attempted to use matplotlib with <code>plt.ion()</code> and <code>plt.pause()</code>, but I couldn't achieve the same smooth dynamic updates. Also, I want to ensure that all updates occur in a single figure.</p>\n<p>Can someone help me write a Python equivalent for this functionality?</p>\n"^^ . "5"^^ . . "0"^^ . "0"^^ . "1"^^ . . . "keyboard"^^ . . . . "0"^^ . . . . "function-reference"^^ . . . "wav"^^ . "<p>I am trying to train a neural network but I am hitting a snag. I have a simplified version of the problem I am facing:</p>\n<h2>Setup:</h2>\n<p><code>NN = trainnet(X_data, Y_data, NN, 'crossentropy', options);</code></p>\n<ul>\n<li><code>X_data</code> is size 25455x3 with each of the 3 columns being normalized (mean = 0 and std = 1)</li>\n<li><code>Y_data</code> is size 25455x1 of values 1 or 0 (binary classification) (<code>sum(Y_data)</code>= 11541(~45%))</li>\n<li><code>NN</code> is a newly generated dlnetwork from the following code:</li>\n</ul>\n<pre class="lang-none prettyprint-override"><code> featureInputLayer(3, &quot;Name&quot;, &quot;InputLayer&quot;)\n fullyConnectedLayer(32, &quot;Name&quot;, &quot;HiddenLayer1&quot;,&quot;WeightsInitializer&quot;, &quot;he&quot;) \n reluLayer(&quot;Name&quot;, &quot;ReLU&quot;)\n dropoutLayer(0.2, &quot;Name&quot;, &quot;Dropout&quot;) \n fullyConnectedLayer(1, &quot;Name&quot;, &quot;OutputLayer&quot;,&quot;WeightsInitializer&quot;, &quot;glorot&quot;)\n sigmoidLayer(&quot;Name&quot;, &quot;SigmoidOutput&quot;) \n];\nNN = dlnetwork(NN);\n</code></pre>\n<ul>\n<li><code>options</code>:</li>\n</ul>\n<pre><code>options = trainingOptions(&quot;adam&quot;, ...\n LearnRateSchedule = &quot;piecewise&quot;, ...\n LearnRateDropFactor = 0.2, ...\n LearnRateDropPeriod = 5, ...\n MaxEpochs = 1, ... \n MiniBatchSize = 128, ...\n ExecutionEnvironment = &quot;cpu&quot;, ...\n Plots = &quot;none&quot;);\n</code></pre>\n<h2>Problem:</h2>\n<p>When I run the single line <code>NN = trainnet(X_data, Y_data, NN, 'crossentropy', options);</code>, the model runs 194 iterations with the final <code>trainingloss</code> being <code>0.044545</code>, however the tested accuracy of the model is only ~45% on similar test data, but more concerning is predictions generated with similar data are very skewed towards one. In fact, the lowest prediction is <code>0.6876</code> and the mean is <code>0.9030</code>. This is a massive jump and one that does not make sense to me. I would expect the model's predictions to stay approximately normal about 0.5 (not considering for the moment any learning) or maybe a bit less to match the slighly lower amount of labels of 1. Why is this happening and how can I fix it?</p>\n<p>Note: What I am really doing is running a loop that runs the line of code I talked about above. The problem I have descibed is just the first iteration of the loop; as it continues, the skew becomes more extreme until all predictions are just 1.00000. The data is different each time through the loop, however it is very similar and there are trends in it that should be learnable (found from other types of regression modeling).</p>\n"^^ . . . "matlab-engine"^^ . "2"^^ . "<p>You can create two fake bar plots with those colors, using <code>NaN</code> values so that the bars are not shown in the graph but they appear in the legend.</p>\n<p>To do this, replace your last line by</p>\n<pre><code>bar(NaN, NaN, 'r') % fake red bar\nbar(NaN, NaN, 'b') % fake blue bar\n\n% Update the legend\nlegend([&quot;m-CAP \\Phi_{1/2}=10°&quot;, &quot;m-CAP \\Phi_{1/2}=30°&quot;, ...\n &quot;m-CAP \\Phi_{1/2}=45°&quot;, &quot;m-CAP \\Phi_{1/2}=60°&quot;, ...\n &quot;DCO-OFDM \\Phi_{1/2}=10°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=30°&quot;, ...\n &quot;DCO-OFDM \\Phi_{1/2}=45°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=60°&quot;, ...\n &quot;Red, \\Phi_{1/2}=60°&quot;, &quot;Blue, \\Phi_{1/2}=60°&quot;], ... % text for red and blue\n 'Location', 'Best');\n</code></pre>\n"^^ . . . "1"^^ . . . . . . . . . "1"^^ . . . "<p>You need to explicitly account for these parameters within your custom loss function.</p>\n<p>Below an example, but adjust accordingly:</p>\n<pre><code>function loss = modelLoss(Y, T, classNames, classWeights)\n\n % normalized to 1\n classWeights = classWeights / sum(classWeights);\n\n mask = ~isnan(T);\n T(isnan(T)) = 0;\n\n numClasses = numel(classNames);\n T_onehot = zeros([size(T, 1), size(T, 2), numClasses, size(T, 4)], 'like', Y);\n for i = 1:numClasses\n T_onehot(:, :, i, :) = (T == i);\n end\n\n % class-wise weighted cross-entropy\n weightedLoss = 0;\n for c = 1:numClasses\n classMask = mask &amp; (T == c);\n weightedLoss = weightedLoss + classWeights(c) * crossentropy(Y(:, :, c, :), T_onehot(:, :, c, :), Mask=classMask);\n end\n\n % Normalize by # of valid pixels\n numValidPixels = sum(mask(:));\n loss = weightedLoss / max(numValidPixels, 1);\nend\n\n\n% Define weights\nclassNames = [...];\nclassWeights = [...]; % Example weights\n\ncustomLoss = @(Y, T) modelLoss(Y, T, classNames, classWeights);\n\nnetTrained = trainnet(images, net, customLoss, options);\n</code></pre>\n"^^ . "Thanks for the solution! Using Formula2 worked a charm."^^ . . "0"^^ . "<p>I'm trying to find normal depth and critical depth using flow parameters with app designer.</p>\n<p>First, I defined the variables globally and set the parameters equal to their abbreviations.\nThen, I defined the all variables and defined function CALCULATEButtonPushed(app, event) for finding normal depth and critical depth.</p>\n<p>When I enter the parameters and run the &quot;Calculate&quot; button, I want to see the normal depth and critical depth in the box.</p>\n<p>When I first ran the code by entering the parameters (BB, ZZ, S0, N, QQ), it was working fine, but today, when I run the &quot;Calculate&quot; button, the system is stuck with a bug. If there is something I missed in the code, I would be glad if you could help me.\n<a href="https://i.sstatic.net/o1o3uiA4.png" rel="nofollow noreferrer">appdesigner image</a></p>\n<pre><code>classdef example &lt; matlab.apps.AppBase\n\n % Properties that correspond to app components\n properties (Access = public)\n UIFigure matlab.ui.Figure\n TabGroup matlab.ui.container.TabGroup\n SteadyTab matlab.ui.container.Tab\n CALCULATEButton matlab.ui.control.Button\n INPUTPARAMETERSLabel matlab.ui.control.Label\n CRITICALDEPTHEditField matlab.ui.control.NumericEditField\n CRITICALDEPTHEditFieldLabel matlab.ui.control.Label\n NORMALDEPTHEditField matlab.ui.control.NumericEditField\n NORMALDEPTHEditFieldLabel matlab.ui.control.Label\n STEADYSTATEDISCHARGEEditField matlab.ui.control.NumericEditField\n STEADYSTATEDISCHARGEEditFieldLabel matlab.ui.control.Label\n MANNINGsVALUEEditField matlab.ui.control.NumericEditField\n MANNINGsVALUEEditFieldLabel matlab.ui.control.Label\n BEDSLOPEEditField matlab.ui.control.NumericEditField\n BEDSLOPEEditFieldLabel matlab.ui.control.Label\n SIDEINCLINATIONEditField matlab.ui.control.NumericEditField\n SIDEINCLINATIONEditFieldLabel matlab.ui.control.Label\n BOTTOMWIDTHmEditField matlab.ui.control.NumericEditField\n BOTTOMWIDTHmEditFieldLabel matlab.ui.control.Label\n Unsteady2DTab matlab.ui.container.Tab\n end\n\n % Callbacks that handle component events\n methods (Access = private)\n\n % Value changed function: BOTTOMWIDTHmEditField\n function BOTTOMWIDTHmEditFieldValueChanged(app, event)\n global BB\n BB = app.BOTTOMWIDTHmEditField.Value;\n \n end\n\n % Value changed function: SIDEINCLINATIONEditField\n function SIDEINCLINATIONEditFieldValueChanged(app, event)\n global ZZ\n ZZ = app.SIDEINCLINATIONEditField.Value;\n \n end\n\n % Value changed function: BEDSLOPEEditField\n function BEDSLOPEEditFieldValueChanged(app, event)\n global S0\n S0 = app.BEDSLOPEEditField.Value;\n \n end\n\n % Value changed function: MANNINGsVALUEEditField\n function MANNINGsVALUEEditFieldValueChanged(app, event)\n global N \n N = app.MANNINGsVALUEEditField.Value;\n \n end\n\n % Value changed function: STEADYSTATEDISCHARGEEditField\n function STEADYSTATEDISCHARGEEditFieldValueChanged(app, event)\n global QQ \n QQ = app.STEADYSTATEDISCHARGEEditField.Value;\n \n end\n\n % Button pushed function: CALCULATEButton\n function CALCULATEButtonPushed(app, event)\n global YNN BB ZZ QQ S0 N YC\n \n\n % function A = AREA(B, YY, Z)\n % A = (B + Z * YY) * YY;\n % end\n \n AREA = @(B, YY, Z) (B + Z*YY) * YY;\n PERI = @(B, YY, Z) B + 2*YY*(1 + Z^2)^0.5; \n \n\n\n % Calculate normal depth\n YNN = 0.01;\n while true\n ETOTAL = (QQ*N)/S0^0.5;\n ECHECK = AREA(BB, YNN, ZZ)^(5/3) / PERI(BB, YNN, ZZ)^(2/3);\n if ETOTAL &lt; ECHECK\n break;\n end\n YNN = YNN + 0.01;\n end\n\n % Calculate critical depth\n W = QQ / (3.132 * BB^2.5);\n if ZZ == 0\n YCOB = W^0.672717 * 1.022785;\n elseif ZZ == 0.5\n YCOB = W^0.602684 * 0.748173;\n elseif ZZ == 1\n YCOB = W^0.574105 * 0.657397;\n elseif ZZ == 1.5\n YCOB = W^0.564345 * 0.625201;\n elseif ZZ == 2\n YCOB = W^0.552851 * 0.584043;\n elseif ZZ == 2.5\n YCOB = W^0.545379 * 0.552333;\n elseif ZZ == 3\n YCOB = W^0.537298 * 0.523298;\n elseif ZZ == 4\n YCOB = W^0.524667 * 0.487638;\n end\n YC = YCOB * BB;\n \n app.NORMALDEPTHEditField.Value = YNN;\n app.CRITICALDEPTHEditField.Value = YC;\n end\n end\n\n % Component initialization\n methods (Access = private)\n\n % Create UIFigure and components\n function createComponents(app)\n\n % Create UIFigure and hide until all components are created\n app.UIFigure = uifigure('Visible', 'off');\n app.UIFigure.Position = [100 100 1016 588];\n app.UIFigure.Name = 'MATLAB App';\n\n % Create TabGroup\n app.TabGroup = uitabgroup(app.UIFigure);\n app.TabGroup.Position = [3 79 1014 492];\n\n % Create SteadyTab\n app.SteadyTab = uitab(app.TabGroup);\n app.SteadyTab.Title = 'Steady';\n\n % Create BOTTOMWIDTHmEditFieldLabel\n app.BOTTOMWIDTHmEditFieldLabel = uilabel(app.SteadyTab);\n app.BOTTOMWIDTHmEditFieldLabel.HorizontalAlignment = 'right';\n app.BOTTOMWIDTHmEditFieldLabel.Position = [21 377 120 22];\n app.BOTTOMWIDTHmEditFieldLabel.Text = 'BOTTOM WIDTH (m)';\n\n % Create BOTTOMWIDTHmEditField\n app.BOTTOMWIDTHmEditField = uieditfield(app.SteadyTab, 'numeric');\n app.BOTTOMWIDTHmEditField.ValueChangedFcn = createCallbackFcn(app, @BOTTOMWIDTHmEditFieldValueChanged, true);\n app.BOTTOMWIDTHmEditField.Position = [156 377 40 22];\n\n % Create SIDEINCLINATIONEditFieldLabel\n app.SIDEINCLINATIONEditFieldLabel = uilabel(app.SteadyTab);\n app.SIDEINCLINATIONEditFieldLabel.HorizontalAlignment = 'right';\n app.SIDEINCLINATIONEditFieldLabel.Position = [30 340 111 22];\n app.SIDEINCLINATIONEditFieldLabel.Text = 'SIDE INCLINATION';\n\n % Create SIDEINCLINATIONEditField\n app.SIDEINCLINATIONEditField = uieditfield(app.SteadyTab, 'numeric');\n app.SIDEINCLINATIONEditField.ValueChangedFcn = createCallbackFcn(app, @SIDEINCLINATIONEditFieldValueChanged, true);\n app.SIDEINCLINATIONEditField.Position = [156 340 40 22];\n\n % Create BEDSLOPEEditFieldLabel\n app.BEDSLOPEEditFieldLabel = uilabel(app.SteadyTab);\n app.BEDSLOPEEditFieldLabel.HorizontalAlignment = 'right';\n app.BEDSLOPEEditFieldLabel.Position = [68 303 73 22];\n app.BEDSLOPEEditFieldLabel.Text = 'BED SLOPE';\n\n % Create BEDSLOPEEditField\n app.BEDSLOPEEditField = uieditfield(app.SteadyTab, 'numeric');\n app.BEDSLOPEEditField.ValueChangedFcn = createCallbackFcn(app, @BEDSLOPEEditFieldValueChanged, true);\n app.BEDSLOPEEditField.Position = [156 303 40 22];\n\n % Create MANNINGsVALUEEditFieldLabel\n app.MANNINGsVALUEEditFieldLabel = uilabel(app.SteadyTab);\n app.MANNINGsVALUEEditFieldLabel.HorizontalAlignment = 'right';\n app.MANNINGsVALUEEditFieldLabel.Position = [29 266 112 22];\n app.MANNINGsVALUEEditFieldLabel.Text = 'MANNING''s VALUE';\n\n % Create MANNINGsVALUEEditField\n app.MANNINGsVALUEEditField = uieditfield(app.SteadyTab, 'numeric');\n app.MANNINGsVALUEEditField.ValueChangedFcn = createCallbackFcn(app, @MANNINGsVALUEEditFieldValueChanged, true);\n app.MANNINGsVALUEEditField.Position = [156 266 40 22];\n\n % Create STEADYSTATEDISCHARGEEditFieldLabel\n app.STEADYSTATEDISCHARGEEditFieldLabel = uilabel(app.SteadyTab);\n app.STEADYSTATEDISCHARGEEditFieldLabel.HorizontalAlignment = 'right';\n app.STEADYSTATEDISCHARGEEditFieldLabel.Position = [253 372 168 22];\n app.STEADYSTATEDISCHARGEEditFieldLabel.Text = 'STEADY STATE DISCHARGE';\n\n % Create STEADYSTATEDISCHARGEEditField\n app.STEADYSTATEDISCHARGEEditField = uieditfield(app.SteadyTab, 'numeric');\n app.STEADYSTATEDISCHARGEEditField.ValueChangedFcn = createCallbackFcn(app, @STEADYSTATEDISCHARGEEditFieldValueChanged, true);\n app.STEADYSTATEDISCHARGEEditField.Position = [436 372 40 22];\n\n % Create NORMALDEPTHEditFieldLabel\n app.NORMALDEPTHEditFieldLabel = uilabel(app.SteadyTab);\n app.NORMALDEPTHEditFieldLabel.HorizontalAlignment = 'right';\n app.NORMALDEPTHEditFieldLabel.Position = [319 295 100 22];\n app.NORMALDEPTHEditFieldLabel.Text = 'NORMAL DEPTH';\n\n % Create NORMALDEPTHEditField\n app.NORMALDEPTHEditField = uieditfield(app.SteadyTab, 'numeric');\n app.NORMALDEPTHEditField.Position = [434 295 40 22];\n\n % Create CRITICALDEPTHEditFieldLabel\n app.CRITICALDEPTHEditFieldLabel = uilabel(app.SteadyTab);\n app.CRITICALDEPTHEditFieldLabel.HorizontalAlignment = 'right';\n app.CRITICALDEPTHEditFieldLabel.Position = [316 258 103 22];\n app.CRITICALDEPTHEditFieldLabel.Text = 'CRITICAL DEPTH';\n\n % Create CRITICALDEPTHEditField\n app.CRITICALDEPTHEditField = uieditfield(app.SteadyTab, 'numeric');\n app.CRITICALDEPTHEditField.Position = [434 258 40 22];\n\n % Create INPUTPARAMETERSLabel\n app.INPUTPARAMETERSLabel = uilabel(app.SteadyTab);\n app.INPUTPARAMETERSLabel.FontWeight = 'bold';\n app.INPUTPARAMETERSLabel.Position = [44 421 127 22];\n app.INPUTPARAMETERSLabel.Text = 'INPUT PARAMETERS';\n\n % Create CALCULATEButton\n app.CALCULATEButton = uibutton(app.SteadyTab, 'push');\n app.CALCULATEButton.ButtonPushedFcn = createCallbackFcn(app, @CALCULATEButtonPushed, true);\n app.CALCULATEButton.Position = [360 224 100 23];\n app.CALCULATEButton.Text = 'CALCULATE';\n\n % Create Unsteady2DTab\n app.Unsteady2DTab = uitab(app.TabGroup);\n app.Unsteady2DTab.Title = 'Unsteady 2D';\n\n % Show the figure after all components are created\n app.UIFigure.Visible = 'on';\n end\n end\n\n % App creation and deletion\n methods (Access = public)\n\n % Construct app\n function app = example\n\n % Create UIFigure and components\n createComponents(app)\n\n % Register the app with App Designer\n registerApp(app, app.UIFigure)\n\n if nargout == 0\n clear app\n end\n end\n\n % Code that executes before app deletion\n function delete(app)\n\n % Delete UIFigure when app is deleted\n delete(app.UIFigure)\n end\n end\nend\n</code></pre>\n"^^ . "1"^^ . "0"^^ . . . "0"^^ . . "0"^^ . . "0"^^ . "<p>I'm relatively new to SPM and related tools, and run into some issues running CAT12 segmentation in batches.</p>\n<p>Individual subjects through the GUI works fine, but when we submit a script to process several subjects, several issues arise:</p>\n<ol>\n<li>issue 1:\nMATLAB:sizeDimensionsMustMatch\nArrays have incompatible sizes for this operation.</li>\n</ol>\n<p>Which arrays is it referring to here? How can I check and correct?</p>\n<ol start="2">\n<li>issue 2:\nMATLAB:UndefinedFunction\nUnrecognized function or variable &quot;VI&quot;.</li>\n</ol>\n<p>Which variable are they referring to?</p>\n<ol start="3">\n<li>issue 3:\nError reading header file</li>\n</ol>\n<p>For some of these issues, some output is still produced, but we struggle to distinguish when a subject has run succesfully. For issue 3, the complete output is not produced.</p>\n<p>We run a bash submission script on a slurm cluster that calls a matlab script for the CAT12 segmentation:</p>\n<p>Bash script:</p>\n<pre><code>#!/bin/bash\n\n#SBATCH --job-name=segmentations_ahead\n#SBATCH --mem=4G\n#SBATCH --partition=luna-cpu-short\n#SBATCH --qos=anw-cpu\n#SBATCH --cpus-per-task=4\n#SBATCH --time=00-03:00:00\n#SBATCH --nice=2000\n#SBATCH --array=1-3%3\n#SBATCH --output=slurm-%A.%a.out\n\n# Load Matlab module\nmodule load matlab/R2021b\nexport MATLABPATH=path/to/cat12\n\ninputdir=path/to/input\n\ncd ${inputdir}\n\nls -d sub-*/ | sed 's:/.*::' &gt; subjects.txt\n\nsubjects=${inputdir}/subjects.txt\nsubj=$(sed -n &quot;${SLURM_ARRAY_TASK_ID}p&quot; ${subjects})\n# random delay\nduration=$((RANDOM % 20 + 2))\necho -e &quot;${YELLOW}INITIALIZING...(wait a sec)${NC}&quot;\necho\nsleep ${duration}\n\n\nmatlab -nodisplay -batch &quot;AHEAD_segmentation $inputdir $subj&quot;\n</code></pre>\n<p>Matlab script:</p>\n<pre><code>function AHEAD_segmentation(inputdir,subj)\n\n% Define paths\naddpath('path/to/spm12');\n\n% Get a list of all subject directories\n%subjects = dir(fullfile(input_dir, 'sub-*'));\n\n% Loop over each subject\n%for i = 1:length(subjects)\n % Define the subject's anat directory within ses-1\n\n subj_dir = fullfile(inputdir, subj, 'ses-1', 'anat');\n % t1_image_gz = fullfile(subj_dir, [subj '_ses-1_acq-wb_mod-t1w_orient-std_brain.nii.gz']);\n t1_image = fullfile(subj_dir, [subj '_ses-1_acq-wb_mod-t1w_orient-std_brain.nii']);\n\n % Show file path\n disp(['Checking: ', t1_image]);\n\n % Check if file exists\n if exist(t1_image, 'file') ~= 2\n fprintf('Warning: File %s not found!\\n', t1_image);\n error('no T1 file'); % Skip to next subject if T1 is missing\n end\n\n % Check if the gzipped T1 image exists\n if ~isfile(t1_image)\n fprintf('T1 image not found for subject %s\\n', subj);\n end\n\n % Print status\n fprintf('Processing subject %s\\n', subj);\n\n % Set up CAT12 batch job for segmentation\n matlabbatch{1}.spm.tools.cat.estwrite.data = {t1_image};\n matlabbatch{1}.spm.tools.cat.estwrite.nproc = 1; \n %matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = {fullfile(spm('path/to/spm12'), 'tpm', 'TPM.nii')}; % Path to SPM's TPM file\n \n spm_dir = spm('dir'); \n\n % Path to TPM file\n tpm_file = fullfile(spm_dir, 'tpm', 'TPM.nii');\n\n % Check if the file exists\n if ~exist(tpm_file, 'file')\n error('TPM file not found: %s', tpm_file);\n end\n\n matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = {tpm_file};\n\n % select modality for SPM\n matlabbatch{1}.spm.tools.cat.estwrite.opts.modality = 'T1'; \n\n % Output options for volume-based analysis\n matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 1; % Disable surface-based outputs\n matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native = 1; % Output native gray matter volume\n matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native = 1; % Output native white matter volume\n matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native = 1; % Output native CSF volume\n matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped = 0; % Output normalized gray matter volume (in MNI space)\n matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped = 0; % Output normalized white matter volume (in MNI space)\n matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped = 0; % Output normalized CSF volume (in MNI space)\n matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod = 0; % Output modulated gray matter volume (useful for VBM)\n matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod = 0; % Output modulated white matter volume\n matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 1]; % Save forward and inverse deformation fields\n\n % Run the CAT12 segmentation\n % spm('defaults', 'FMRI');\n % spm_jobman('initcfg');\n spm_jobman('run', matlabbatch);\n</code></pre>\n<p>Any thoughts on how to tackle any of these three issues (or links to similar issues/documentation/FAQ) would be greatly appreciated!</p>\n"^^ . "0"^^ . . . . . "0"^^ . "<p>I want to Publish on a web page a LaTeX expression built with the Matlab <code>latex</code> function. I am using the native Publish button.\nI can Publish this expression, only if I write it directly:</p>\n<pre><code>% $P(s) = s^3+6\\,s^2+11\\,s+6$\n</code></pre>\n<p>Is there any way to Publish the same expression, but from a LaTeX variable?\nEvenmore, how to Publish the LaTeX variable within a nested HTML code?\nI understand it could be not possible, since Publishing is made from a comment line, but, could I built a comment expression from a string?</p>\n<p>This is the code I wrote:</p>\n<pre class="lang-matlab prettyprint-override"><code>%% Publish LaTeX in HTML\n% How to publish a variable LaTeX\n%% Polynomial\n% Define p(x) polynomial, and simbolic and LaTeX strings\nsyms s\nP = [1,6,11,6] % Defining P(s) polynomial (numeric treatment)\nsymP = poly2sym(P,s) % symbolic string\npretty(symP) % display pretty form\nltxP = latex(symP) % LaTeX string\n%% Publish in HTML\n% Publishing P(s) in HTML is posible with the direct description of the\n% polynomial:\n%\n% $P(s) = s^3+6\\,s^2+11\\,s+6$\n%\n% But, how to publish the same polynomial P(s) from the LaTeX variable?\n%\n% $P(s) = ltxP$\n%\n% &lt;html&gt;\n% &lt;p style=&quot;font-family:Times; font-size:large;&quot;&gt;\n% Evenmore, how to publish the LaTeX variable within a nested HTML code? is\n% this possible?&lt;/p&gt;\n% &lt;p&gt;$P(s)=ltxP$&lt;br&gt;\n% \\(P(s)=ltxP\\)&lt;br&gt;\n% $$P(s)=ltxP$$&lt;/p&gt;\n% &lt;/html&gt;\n</code></pre>\n"^^ . "0"^^ . . "Well, did you look at the documentation? https://www.mathworks.com/help/stats/classificationdiscriminant.html#bs1qffl-1_sep_shared-Coeffs : "The equation of the boundary between class `i` and class `j` is `Const + Linear * x + x' * Quadratic * x = 0`, where x is a column vector of length p." That doesn't look anywhere near what you're doing."^^ . "Unrelated: don’t use `clear all`. `clear`, by itself, clears all variables from the workspace. `clear all` also unloads all functions you’ve used previously, which only serves to slow MATLAB down the next time you call those functions. https://www.mathworks.com/help/matlab/ref/clear.html — Also, `clear variables` is the same as `clear`."^^ . . . "I have just spotted the `^M` carriage return character in my final code snippet. So this suggests that the `m2cpp.pl` filter has a Windows-style line ending in the opening line `#!/usr/bin/perl.exe`, which is confusing the Unix-based Docker container. Not sure how to remove this."^^ . "<p>While migrating to Python from Matlab, I get different result for StateSystem transform.\nIn Matlab,there is a 2 in 2 out system:</p>\n<p>tf1 =</p>\n<pre><code> -4\n --------------------------------\n 1e06 s^3 + 30000 s^2 + 300 s + 1 \n</code></pre>\n<p>Numerator: {[0 0 0 -4]}<br />\nDenominator: {[1000000 30000 300 1]}</p>\n<p>tf2 =</p>\n<pre><code>0\n</code></pre>\n<p>Numerator: {[0 0 0]}<br />\nDenominator: {[5600 150 1]}</p>\n<p>tf3 =</p>\n<pre><code> 0.75\n --------------------\n 5600 s^2 + 150 s + 1\n</code></pre>\n<p>Numerator: {[0 0 0.7500]}\nDenominator: {[5600 150 1]}</p>\n<p>MatlabCode:</p>\n<pre class="lang-none prettyprint-override"><code>sys=[tf1,tf2;tf3,0];\nsys_ss=ss(sys);\n</code></pre>\n<p>the output is:</p>\n<pre><code>sys_ss =\n \n A = \n x1 x2 x3 x4 x5\n x1 -0.03 -0.0192 -0.008192 0 0\n x2 0.01562 0 0 0 0\n x3 0 0.007812 0 0 0\n x4 0 0 0 -0.02679 -0.01143\n x5 0 0 0 0.01562 0\n \n B = \n u1 u2\n x1 0.25 0\n x2 0 0\n x3 0 0\n x4 0.125 0\n x5 0 0\n \n C = \n x1 x2 x3 x4 x5\n y1 0 0 -0.1311 0 0\n y2 0 0 0 0 0.06857\n \n D = \n u1 u2\n y1 0 0\n y2 0 0\n</code></pre>\n<p>In Python,I use control.ss:</p>\n<pre class="lang-py prettyprint-override"><code>import control\n\nnum11 = [0,0,0,-4]\nnum12 = [0,0,0]\nnum21 = [0,0,0.7500]\nnum22 = [0]\n\nrow1 = [num11, num12]\nrow2 = [num21, num22]\nnumerator = [row1, row2]\ndenominator = [\n [[1000000, 30000, 300,1], [5600,150,1]],\n [[5600,150,1], [1]]\n ]\nG = control.tf(numerator,\n denominator)\ncontrol.ss(G )\n</code></pre>\n<p>Then I got StateSpace:\n<a href="https://i.sstatic.net/8MG41EBT.png" rel="nofollow noreferrer">enter image description here</a></p>\n<p>What am I missing here? How can I fix to get the exact same result?</p>\n"^^ . "2"^^ . "how would you add variables when using system ? I have tried this: system(sprintf('python "%s" "%s" "%s"', 'Merge_CT_MRI_targets.py', num2str(OriginalPatients(index_target)), num2str(target_list(index_target))));\nbut it doesn't seem to load the variables correctly"^^ . . . "0"^^ . . . . . . . "@Diusha Maybe turn off the menus? See the `MenuBar` option: https://www.mathworks.com/help/matlab/ref/matlab.ui.figure-properties.html#d126e527403"^^ . "0"^^ . "1"^^ . "@CrisLuengo I'm not sure how to explain without sounding condescending and I believe you are causing an xy problem, please re-read the question carefully.\n\nIn the example they have 2 variables, x1 and x2. I want to use only 1 variable not 2... so just x1, with y1 being the control variable, similar to fig 1 in my code. \n\nYou state "You need to use both co-ords.. if you want to draw anything other than a vertical line" I'm afraid y = x^2 begs to differ.\n\nI am ignoring the linear because I want quadratic discriminant analysis. You may be correct that this is wrong... but what is right?"^^ . . . "0"^^ . . . . . . . . . "<p>After using <code>mat2cell</code>, you can concatenate the 2D matrices into a 3D matrix with</p>\n<pre><code>m = cat( 3, m{:} );\n</code></pre>\n<p>This will satisfy <em>&quot;m{1} becomes m(:, :, 1)&quot;</em> etc.</p>\n<hr />\n<p>A different option would be to take each strip of <code>N</code> rows and <code>reshape</code> them directly into an <code>NxNxN</code> matrix of segments, assigning them as the next chunk of the <code>NxNx(N^2)</code> output matrix</p>\n<pre><code>m = NaN(N,N,N^2);\nfor ii = 1:N:N^2\n m(:,:,ii:(ii+N-1)) = reshape( M(ii:(ii+N-1),:), N, N, N );\nend\n</code></pre>\n<p>Note that the segments in these two options are in a different order (the first goes down then across for sub-matrices, the latter goes across then down). If you wanted this loop and reshape version to match the <code>mat2cell</code> version exactly you would need to do a couple of transpose operations with the <code>reshape</code> to get the ordering right</p>\n<pre><code>m = NaN(N,N,N^2);\nfor ii = 1:N:N^2\n m(:,:,ii:(ii+N-1)) = pagetranspose( reshape( M(:,ii:(ii+N-1)).', N, N, N ) );\nend\n</code></pre>\n<p>There is only a very small performance penalty for doing the additional transpose operations.</p>\n<hr />\n<p><strong>Update with benchmarking</strong></p>\n<p>I was curious which of the options above would be faster, so wrote the benchmark at the bottom here (wrapper for the code suggested in the answer above). Here is the resulting plot, so looping and assigning directly into a numeric matrix is faster than going via a cell regardless of <code>N</code>:</p>\n<p>I've also included <a href="https://stackoverflow.com/a/79365537/3978545">chtz's answer</a> which just uses <code>reshape</code> and permute, and gives the same result as the <code>mat2cell</code> and <code>pagetranspose</code> options above much faster, and with less dependency on <code>N</code>, <strong>so I would recommend their solution</strong>.</p>\n<p>I've also included <a href="https://stackoverflow.com/a/79365809/3978545">Luis' answer</a> for completeness.</p>\n<p><a href="https://i.sstatic.net/QLBf4YnZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QLBf4YnZ.png" alt="benchmarking results" /></a></p>\n<p>Benchmarking code:</p>\n<pre><code>Nmax = 17;\nt = zeros(Nmax,2);\nfor N = 2:Nmax\n M = (1:N^2) + 0.1*(1:N^2).';\n \n t(N,1) = timeit( @() opt1(N,M) );\n t(N,2) = timeit( @() opt2(N,M) );\n t(N,3) = timeit( @() opt3(N,M) );\n t(N,4) = timeit( @() opt4(N,M) );\n t(N,5) = timeit( @() opt5(N,M) );\nend\n\nfigure(1); clf; hold on; grid on; legend( 'show', 'fontsize', 14 );\nplot( 1:Nmax, t(:,1), 'displayname', 'mat2cell and cat', 'linewidth', 2 );\nplot( 1:Nmax, t(:,2), 'displayname', 'loop and reshape', 'linewidth', 2 );\nplot( 1:Nmax, t(:,3), 'displayname', 'loop and reshape (2)', 'linewidth', 2 );\nplot( 1:Nmax, t(:,4), 'displayname', 'reshape and permute', 'linewidth', 2 );\nplot( 1:Nmax, t(:,5), 'displayname', 'im2col', 'linewidth', 2 );\nylabel( 'Time (sec)' );\nxlabel( 'N' );\n\nm = opt3( N, M );\n\nfunction m = opt1( N, M )\n m = mat2cell(M, N * ones(1, size(M, 1) / N), ...\n N * ones(1, size(M, 2) / N));\n \n m = cat( 3, m{:} );\nend\nfunction m = opt2( N, M )\n m = NaN(N,N,N^2);\n for ii = 1:N:N^2\n m(:,:,ii:(ii+N-1)) = reshape( M(ii:(ii+N-1),:), N, N, N );\n end\nend\nfunction m = opt3( N, M )\n m = NaN(N,N,N^2);\n for ii = 1:N:N^2\n m(:,:,ii:(ii+N-1)) = pagetranspose( reshape( M(:,ii:(ii+N-1)).', N, N, N ) );\n end\nend\nfunction m = opt4( N, M )\n m = reshape(permute(reshape(M, N,N,N,N), [1,3, 2,4]), N,N, N*N);\nend\nfunction m = opt5( N, M )\n m = reshape(im2col(M, [N N], 'distinct'), N, N, []);\nend\n</code></pre>\n"^^ . . . . . "<p>I’m facing a blocking issue with MATLAB Runtime in a COM-registered Windows Forms Control Library inside an external application.</p>\n<p>The issue arises when I instantiate a MWArray (or anything from the MATLAB Runtime), throwing a TypeInitializationException.</p>\n<p>Exception:</p>\n<pre><code>System.TypeInitializationException\n HResult=0x80131534\n Message=The type initializer for 'MathWorks.MATLAB.NET.Arrays.MWNumericArray' threw an exception.\n Source=MWArray\n StackTrace:\n at MathWorks.MATLAB.NET.Arrays.MWNumericArray..ctor(Double scalar)\n at TestWindowsFormsControlLibrary.UserControl1..ctor() in ...\\SandboxSolution\\TestWindowsFormsControlLibrary\\UserControl1.cs:line 32\n\n This exception was originally thrown at this call stack:\n [External Code]\n\nInner Exception 1:\nTypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Arrays.MWArray' threw an exception.\n\nInner Exception 2:\nTypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception.\n\nInner Exception 3:\nException: Trouble initializing libraries required by .NET Assembly.\n</code></pre>\n<p><strong>In other words:</strong></p>\n<ul>\n<li>The issue occurs only when the control library is COM-registered and loaded in an external application (e.g., Excel).</li>\n<li>Without the COM registration, the same control works perfectly in a standalone Windows Forms App or WPF application.</li>\n</ul>\n<p><strong>Error Trigger Code</strong></p>\n<p>The exception occurs when initializing MWArray like so:</p>\n<p><code>MWArray test = new MWNumericArray(0);</code></p>\n<ul>\n<li>If I remove this line, the COM application runs fine (no interaction with MATLAB Runtime).</li>\n<li>If I run the same control in a standard Windows Forms App or WPF App, it loads the MATLAB Runtime without issues.</li>\n</ul>\n<p><strong>Steps to reproduce:</strong></p>\n<ol>\n<li>Create a Windows Forms Control Library.</li>\n<li>Set up as described in MATLAB documentation.</li>\n<li>Use the MATLAB Runtime library (e.g., initialize a MWArray).</li>\n<li>Build and test it within a Windows Forms App or WPF App — it works fine.</li>\n<li>Register the control as a COM component and use it in an external application (e.g., Excel).</li>\n<li>The TypeInitializationException is thrown.</li>\n</ol>\n<p><strong>Environment</strong></p>\n<ul>\n<li>MATLAB Runtime version: 2024b 64-bit</li>\n<li>.NET Framework: 4.8.1 64-bit</li>\n<li>COM architecture: Only 64-bit (AnyCPU is removed)</li>\n</ul>\n<p><strong>Expected result:</strong></p>\n<p>I expect the MATLAB Library works in the COM-registered control as the Windows Forms Application.</p>\n<p><strong>Additional notes:</strong> I have only one MATLAB Runtime installed. I have it added in the PATH and it is the only entry.</p>\n"^^ . "cell-array"^^ . "The image shows “τ”, but your text says “2”. Is that intentional?"^^ . "reinforcement-learning"^^ . "0"^^ . "<p>I am running certain part of a python code in MATLAB, that brings problems. I have python 3.11.9, and MATLAB 2023b. However, the same part of the code runs perfectly in vscode. It is related to the itk-elastix python library (which im running the 0.21.0 version)\nThe python code:</p>\n<pre><code>\nimport itk\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom scipy.ndimage import rotate\nimport scipy.ndimage as ndi\nimport ipywidgets as widgets\nfrom ipywidgets import interact, IntSlider\n\nimport time\n\n## Merge CT from patient XXXX and targets from YYYY\n\nos.chdir('C:/Users/Admin/...')\nprint(&quot;Test0&quot;)\nnr = '0000'\nMRh = itk.imread(&quot;NIIFT/MRI_&quot;+nr+&quot;.nii&quot;, itk.F)\nCTh = itk.imread(&quot;NIIFT/CT_&quot;+nr+&quot;.nii&quot;, itk.F)\nprint(&quot;Test1&quot;)\n\nfixed_image = CTh\nresize_factor = 1\nmoving_image = MRh\nprint(&quot;Test2&quot;)\n\nparameter_object = itk.ParameterObject.New()\nparameter_object.ReadParameterFile(&quot;ParametersRigid.txt&quot;)\nprint(&quot;Test3&quot;)\n</code></pre>\n<p>This is the part of the code that brings me problems:</p>\n<pre><code>result_image, rigid_parameters = itk.elastix_registration_method(\nfixed_image, moving_image,\nparameter_object=parameter_object,\nlog_to_console=False)\nprint(parameter_object)\nprint(&quot;Test4&quot;)\n\nitk.imwrite(result_image, &quot;NIIFT/MRI_Corr_&quot;+nr+&quot;.nii&quot;)\nprint(&quot;Test5&quot;)\n</code></pre>\n<p>I run it in MATLAB, with the following code:</p>\n<pre><code>pyrunfile(&quot;Merger_CT_X_TARGET_Y.py&quot;);\n</code></pre>\n<p>And it brings the error:</p>\n<pre><code>&gt;&gt; MergeFromMatlab\nTest0\nTest1\nTest2\nTest3\n(...some prints here)\n\nError using py.exec\nPython process terminated unexpectedly. To restart the Python interpreter, first call &quot;terminate(pyenv)&quot; and then call a Python function.\n\nError in MergeFromMatlab (line 3)\npyrunfile(&quot;Merger_CT_X_TARGET_Y.py&quot;);\n</code></pre>\n<p>Whenever this error happens, I have to restart MATLAB. The part of the code before 'Test 4' works correctly. I would appreciate some help</p>\n"^^ . "2"^^ . . . . . . . . . . "Welcome to Stack Overflow. What's printed out when your run the script? Given that you did include print() statements, some sort of print sequences should appear. I'm not familiar with Matlab so dunno what happens with stdout output."^^ . "0"^^ . . . . . "<p>I was looking to find a way to get essential matrix in opencv.</p>\n<p>I found these two links that was for the function:\n<a href="https://docs.opencv.org/3.4/d9/d0c/group__calib3d.html#ga0b166d41926a7793ab1c351dbaa9ffd4" rel="nofollow noreferrer">https://docs.opencv.org/3.4/d9/d0c/group__calib3d.html#ga0b166d41926a7793ab1c351dbaa9ffd4</a></p>\n<p>and</p>\n<p><a href="https://amroamroamro.github.io/mexopencv/matlab/cv.findEssentialMat.html" rel="nofollow noreferrer">https://amroamroamro.github.io/mexopencv/matlab/cv.findEssentialMat.html</a></p>\n<p>In the second link you can see on top this &quot;cv.findEssentialMat - MATLAB File Help &quot;. I was confused. Is it using Matlab somewhow? Because I would like not to do it then.</p>\n<p>Thanks!</p>\n"^^ . . . "2"^^ . . . . "2"^^ . . "0"^^ . . . . . . "What could be the cause of my SPM CAT12 preprocessing errors?"^^ . . . . . "0"^^ . . . . . . "0"^^ . "0"^^ . "2"^^ . . "0"^^ . . . "0"^^ . . "continuous-integration"^^ . "0"^^ . . "0"^^ . . . . . . "0"^^ . "1"^^ . . . . . . . "fft"^^ . "0"^^ . "1"^^ . . . "0"^^ . "0"^^ . . . . . . . . "matlab"^^ . . "This will not preserve the same order as in the OP's described output, for example the first 3x3 "segment" would just be a reshaped version of the first column, rather than the upper-right 3x3 submatrix"^^ . "1"^^ . . "0"^^ . . . . . "'variables' passed on the commandline to python need to be read into python variables , use the sys module. variable1=sys.argv[1] , variableN= sys.argv[n] etc"^^ . "1"^^ . . "I have another question. If I wanted to do 1D quadratic discriminant (i.e. find the boundary with only the x axis as the variable, y axis as a control), how would I modify this answer? I guess you might want me to post another question, but if we can do it here I figure we can save cluttering the forums with my obscure ideas!"^^ . . "5"^^ . . . "Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)."^^ . . . . . "I'm not sure it will help but it might be that just setting `FILTER_SOURCE_FILES=YES` might help as the call / caller graphs are generated based on the results of same lexer that is used for `SOURCE_BROWSER = YES`. Note the current doxyge version is 1.13.2, but I don't think this has a lot of effect on your problem."^^ . . . . "0"^^ . . "surface"^^ . . . "<p>The limitations of using the MATLAB interface to SQLite are:</p>\n<ul>\n<li>NULL values are not supported as the first value in any column.</li>\n</ul>\n<p><a href="https://in.mathworks.com/help/database/ug/interact-with-data-in-sqlite-database-using-matlab-interface-to-sqlite.html" rel="nofollow noreferrer">Reference</a></p>\n<p>The possible workaround to use <code>NaN</code></p>\n<pre><code>insert(conn, 'example_table', {'id', 'name', 'age'}, {1, 'John', NaN});\n</code></pre>\n<p>where <code>NaN</code> is an empty string in the database</p>\n"^^ . "<p>I am trying to launch a python script from within matlab.</p>\n<pre><code>system('python3 /home/niuniek/meldog-ros/src/power_unit_v3/launch/power_unit_run_simulation_node.py')\n</code></pre>\n<p>This script launches gazebo and a ros2 node for sending trajectories into a simulation.</p>\n<pre><code>def launch_gazebo_simulation():\n # Open a new terminal and launch Gazebo simulation\n p1 = subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', 'cd meldog-ros &amp;&amp; timeout 13s ros2 launch power_unit_v3 power_unit_v3_optimization.launch.py'])\n time.sleep(13)\n p2 = subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', 'killall ruby'])\n\nif __name__ == '__main__':\n # launch_gazebo_simulation()\n launch_gazebo_simulation()\n</code></pre>\n<p>This python script executes just fine from a regular terminal, but when i try to launch the matlab program, gazebo does not launch and i get this error message:</p>\n<pre><code>[ruby $(which ign) gazebo-2] Library error for [/usr/lib/x86_64-linux-gnu/libignition-gazebo6-ign.so.6.16.0]: /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5: undefined symbol: _ZN18QTextureGlyphCache8populateEP11QFontEngineiPKjPK11QFixedPoint, version Qt_5_PRIVATE_API\n[ERROR] [ruby $(which ign) gazebo-2]: process has died [pid 16310, exit code 255, cmd 'ruby $(which ign) gazebo -r -v -v4 empty.sdf --force-version 6'].\n</code></pre>\n<p>I've tried launching Matlab from root and it didnt work, i also tried using a different terminal (xterm, terminator) to no effect.</p>\n"^^ . "0"^^ . . . . . "0"^^ . "<p>I have a Matlab code under this form:</p>\n<pre><code>clear all; close all; clc; clear variables;\nfolder = fileparts(which(mfilename)); \n\n% Add that folder plus all subfolders to the path.\naddpath(genpath(folder));\ndata_folder=&quot;D:\\Trucmuche\\2024&quot;;\n\nproportion_list=[1, 11];\nmixing_times_list=[&quot;000&quot;, &quot;015&quot;, &quot;030&quot;, &quot;060&quot;, &quot;120&quot;];\n\n\nfor i=1:length(proportion_list)\n this_prop=proportion_list(i);\n for j=1:length(mixing_times_list)\n rehash;\n this_mixing_time=mixing_times_list(j);\n browse_and_filter(data_folder, this_prop,this_mixing_time);\n disp(&quot;Success ! Moving to the next one !&quot;);\n end\nend\n</code></pre>\n<p>and the function is</p>\n<pre><code>function browse_and_filter(root_folder, this_prop, this_mix_time)\n \n if isfolder(root_folder)\n disp(['Great ! The folder &quot;', root_folder, '&quot; exists.']);\n else\n disp(['Bad :-( The folder &quot;', root_folder, '&quot; does not exist.']);\n end\n \n % Get all rank_1 directories in the root folder\n rank_1_dirs = dir(root_folder);\n rank_1_dirs = rank_1_dirs([rank_1_dirs.isdir] &amp; ~startsWith({rank_1_dirs.name}, '.'));\n disp({rank_1_dirs.name});\n ...\n</code></pre>\n<p>The problem is that, for the (two, but this even seems inconsistent) first iterations in the main code (the &quot;ij&quot; loop let's say), this works well and I get the following:</p>\n<blockquote>\n<p>&quot;Great ! The folder &quot;&quot; &quot;D:\\Trucmuche\\2024&quot; &quot;&quot; exists.&quot;</p>\n</blockquote>\n<blockquote>\n<p>{'0716'} {'0717'} {'0718'} {'0719'}</p>\n</blockquote>\n<p>where these lasts are the (expected) outcome of disp({rank_1_dirs.name});</p>\n<p>However, at some iteration, for some reason I don't understand, I get this</p>\n<blockquote>\n<p>&quot;Great ! The folder &quot;&quot; &quot;D:\\Trucmuche\\2024&quot; &quot;&quot; exists.&quot;</p>\n</blockquote>\n<p>but the next line (i.e. the list of subfolders) remains empty which is not what I expect...</p>\n<p>There are surely workarounds to alleviate this since the outcome is the same at every iteration of the loop, I can refactor the code but still I was wondering why do I have this inconsistent behaviour ? I am doing a write operation at the end of the code of each iteration but not in <code>&quot;D:\\Trucmuche\\2024&quot;</code>. Also, I added a one second pause after each iteration to alleviate the possible effect of writing operations but this did nothing.</p>\n<p>Any clue about that ?</p>\n"^^ . . . . . . . "0"^^ . "0"^^ . "@user2587726 no worries, glad it worked for you with that change"^^ . "0"^^ . . . "0"^^ . . . . "MatLab 2023a App Designer stuck when opening a .mlapp file created by 2024a"^^ . . "0"^^ . . "plot"^^ . "0"^^ . "Segmenting Shortest Paths in Simple Virtual Reality Map Images"^^ . "@Compo Thank you for taking the time to edit the question and providing a helpful comment. Can you clarify why I would use `/C` or `/K`? `/C` `/K` Reference: https://ss64.com/nt/cmd.html. If that somehow elevates privilege, I would encourage you to post an answer."^^ . "flutter"^^ . . "1"^^ . "@Diusha That must be a Windows issue then. I can't reproduce that on my Mac. Each of the modifier keys results in an event. Maybe a Windows user knows how to fix that."^^ . "2"^^ . . . "<pre><code>fp = fopen('Img.dat', 'rb');\ndata = fread(fp, 'float');\nfclose(fp);\ndata = reshape(data,[512, 512, 242]);\n\ntheta = [0 15 0];\ntransl = [0 0 0];\ntform = rigidtform3d(theta,transl);\n\ndata_rotated = imwarp(data,tform,'cubic');\nfigure;imshow(data_rotated(:,:,180)',[]);\n</code></pre>\n<p>I tried the above matlab code, where the inpute images in 'Img.dat' is as follows:<br>\n<a href="https://i.sstatic.net/8Mxc8ElT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8Mxc8ElT.png" alt="enter image description here" /></a></p>\n<br>\n<p>However, there are <strong>horizontal stripes</strong> in the result, which is 'data_rotated', as shown below:<br>\n<a href="https://i.sstatic.net/wyVTJrY8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wyVTJrY8.png" alt="enter image description here" /></a></p>\n<br>\n<p>The difference between the above two images is that the input image has a relatively uniform noise distribution, while the output image has an uneven noise distribution, with higher noise at the red arrow in the above figure, resulting in stripes in the image.</p>\n<p>This reason seems to be related to the interpolation method of the MATLAB function imwarp. So how to eliminate this phenomenon?</p>\n"^^ . . "Most promising way in this case seems putting this question on matlab central and wait for a matlab developer getting along to help you. The developers are very active in matlab central community and may unveil undocumented functionalities. Sorry stackoverflow :-)"^^ . . . . "0"^^ . . . . . . . . "For clarity, I think the issue with the code is L147 and onwards. \n\n'f12 = @(x1)...'\n\nOn fig2, the boundaries between the groups just aren't there."^^ . . . . "0"^^ . "i have been trying to do it by defining the variables in python, like: target = sys.argv[0]; patient = sys.argv[1]"^^ . . "<p>I have <a href="https://figshare.com/s/936cf9f0dd25296495d3" rel="nofollow noreferrer">this data set</a> which is recorded from 50 children with FMCW radar to detect their heart rate and respiration rate. I am using this data set and I want to just calculate the range FFT and after that applying Doppler FFT in one of the receivers of it. The size of raw data is 4 ** 512 ** 6,000, where 4 is the number of receivers, 512 is the number of samples of each frame and 6,000 (60 * 5 minutes * 20 frames per second) is the number of all the frames.</p>\n<p>I have the following code but the Doppler_fft of all the windows gives me the same peak and it seems that the heart is not moving at all. I have used the 30 second windows (which includes 600 frames of 1,200 chirps) and I'm sliding the window in each loop. According to the Range_FFT plot the maximum peak of range_fft is in the 37th sample so the Doppler_FFT_goal shows the doppler fft of the exact location of the target.</p>\n<pre><code>close all\nclear\nclc\n%% Select Participant Number ( 1 - 50 )\n\nParticipantNum = 1;\n\nif ( ParticipantNum &lt; 1 || ParticipantNum &gt; 50 )\n disp('Wrong Participant Number')\n return;\nend\n\n%% Set Parameters\n\npara = f_Parameter();\n\n%% Read CSV Data\n\n% read radar rawdata\nfid = fopen(['Rawdata\\FMCW Radar\\Rawdata\\Rawdata_' num2str(ParticipantNum) '.csv']);\ntstream = textscan(fid, '%d', 'Delimiter', ',');\ntstream = tstream{1,1};\nstreamsize = size(tstream,1)/para.AntNum;\nRawdata = zeros(para.AntNum, streamsize);\nfor i = 1:para.AntNum\n \n Rawdata(i,:) = tstream((i-1)*streamsize+1:i*streamsize);\n \nend\nfclose(fid);\n\nrefBRFilePath = ['C:\\mydata\\Nihon Kohden\\Heart Rate &amp; Breathing Rate\\Ref_Breath_' num2str(ParticipantNum) '.csv'];\nrefHRFilePath = ['C:\\mydata\\Nihon Kohden\\Heart Rate &amp; Breathing Rate\\Ref_Heart_' num2str(ParticipantNum) '.csv'];\nRef_BR = csvread(refBRFilePath);\nRef_HR = csvread(refHRFilePath);\n\n%% Reshape Radar RawData to Signal Processing\n\nRawData = reshape(Rawdata, para.AntNum, para.adcsample*para.chirploops, para.datalength);\n%% plot the first frame of the first RX antena\nt = 3.3333e-07:512/3000000/512: 512/3000000 *(20*60*5) ;\nfigure(1)\nplot(t(1:512),abs(reshape(RawData(1,:,1),1,512)))\nhold on\nplot(t(1:512),imag(reshape(RawData(1,:,1),1,512)))\ntitle(&quot;the IF signal of the first frame and RX antena&quot;)\nlegend(&quot;real part&quot;,&quot;imaginary part&quot;)\nylabel(&quot;amplitude&quot;)\nxlabel(&quot;time&quot;)\n\n%% calculations of range\n% fft(exp(j*w0*t)) ==&gt; 2*pi*delta(w-w0) ==&gt; w0=2*pi*BW*tdelay / Tchirp \n% tdelay= w0* Tchirp / 2*pi*BW ==&gt; tdelay = 2*distance / c\n% distance = w0 *Tchirp *c / 4* pi*BW \n%w0=2*pi*fbeat ==&gt; distance(range) = fb*Tchirp*c / 2*BW\n\n\n\n%% range fft\nMix= reshape(squeeze(RawData(1,:,:)),256,12000); \nN= 1024;\nRange_FFT = zeros(N,12000);\nfor i=1:12000\n Range_FFT (:,i) = fft(Mix(:,i),N);\nend\n\nFs =para.samplerate; \n% Range_FFT = fft(Mix(:,1),N),1;\n%freq = linspace(0, para.fps/2, length(Range_FFT(1:N/2,1))); \nfreq = (0:(N-1)/2)*(Fs/N);\n\nRange = (freq *para.c)/(2*para.freqslope);\nfigure('Name',&quot;one sided range fft of one chirp 1-20 vs range&quot;)\nplot(Range,abs(Range_FFT(1:N/2,1)));\n\n\n% doppler fft with 30 seconds windows \nDoppler_FFT_goal =zeros(12000-1201,1200);\nDoppler_FFT_useless =zeros(12000-1201,1200);\nfor i=1:12000-1200\n Doppler_FFT_goal(i,:)=fftshift(fft(Range_FFT(38,i:i+1199),[],2));\n Doppler_FFT_useless(i,:)=fftshift(fft(Range_FFT(100,i:i+1199),[],2));\nend\n\nfreq_doppler = (1:1200)*(Fs/1200);\nvelocity = para.lambda*(abs(freq_doppler))/ 2*pi*(2*para.tc) ; % v= (lambda*f) / 4*pi*Tc\nfigure(5)\nplot(velocity,abs(Doppler_FFT_goal(1,:)));\nhold on\nxlabel(&quot;velocity (m/s)&quot;);\nylabel(&quot;the doppler FFT 0f chirps&quot;);\nplot(velocity,abs(Doppler_FFT_goal(2,:)));\nlegend(&quot;the first 30 seconds&quot;,&quot;the second 30 seconds&quot;)\n</code></pre>\n<p>here is the files related to the first participant of data set,the article for this dataset and my code(edditor.m).\n<a href="https://drive.google.com/drive/folders/1-lnWeh7_26bcN0zCqhCjjHpvuNd2biSA?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/drive/folders/1-lnWeh7_26bcN0zCqhCjjHpvuNd2biSA?usp=sharing</a></p>\n"^^ . . . "matrix"^^ . . . . "0"^^ . "graphviz"^^ . "For such a small example it's hard to definitively suggest what the fastest approach might be, presumably if this is too slow then your real input is significantly larger?"^^ . "0"^^ . . . . . . . . . "0"^^ . . "Doxygen cannot see `m2cpp` filter inside of container"^^ . "1"^^ . . . . "0"^^ . "0"^^ . . . . "0"^^ . . . . "But a 2D discriminant function cannot, in general, be written in the form f(x), you need to use `fimplicit` with f(x,y)."^^ . . . "0"^^ . . . "@CrisLuengo, I need the main loop. The program should interact with user and with a device via a COM port using a special protocol with time intervals.\nIn this example, I added `plot` for the sole purpose: try to open the Figure window not after exiting the loop, but before"^^ . . . "1"^^ . . "1"^^ . . "2"^^ . . "nonlinear-optimization"^^ . "signal-processing"^^ . "1"^^ . . . . "2"^^ . "Well technically, as previously mentioned, it is good practice to doublequote arguments, that could be ```%SystemRoot%\\System32\\cmd.exe /D /C ""P:\\athTo\\myBatchfile.bat""```; _(one set for the `/C` argument and one for the batch file name)_."^^ . . . . "0"^^ . . . "c#"^^ . . . "2"^^ . "FYI That’s not a nested function. In MATLAB, the term “nested function” has a specific meaning: a function defined inside the body of another function, where it has access to the parent’s variables."^^ . . . . . . . . . . . . "Which version of doxygen are you using? (`PERL_PATH` has been removed in doxygen version 1.8.16, current version is 1.13.0) Furthermore the `PERL_PATH` didn't have anything to do with the `FILTER_PATTERNS`, here it is required to have the place of the perl executable in the system path or use `*.m=/usr/bin/perl /usr/local/bin/m2cpp.pl`"^^ . . "<p>From the <a href="https://uk.mathworks.com/help/stats/classificationdiscriminant.html" rel="nofollow noreferrer"><code>classificationdiscriminant</code></a> docs, we have</p>\n<blockquote>\n<p><code>Const</code> — A scalar<br>\n<code>Linear</code> — A vector with p components, where p is the number of columns in X<br>\n<code>Quadratic</code> — p-by-p matrix, exists for quadratic DiscrimType</p>\n<p>The equation of the boundary between class i and class j is\n<br><code>Const + Linear * x + x' * Quadratic * x = 0</code>\n<br>where x is a column vector of length p.</p>\n</blockquote>\n<p>You could work out all of the matrix coefficients for the quadratic term by multiplying and writing out <code>x'Qx</code>, which you've done (with or without realising) already for the linear coefficients.</p>\n<p>However, it's easier to just treat this as a matrix equation and write a function which accepts <code>x1,x2,x3</code> and evaluates the boundary using the matrices.</p>\n<p>You can do this by making a local function <code>fKLQ(K,L,Q,x1,x2,x3)</code> which you can alias with your existing anonymous function handles <code>f12</code> etc like so:</p>\n<pre><code>f12 = @(x1,x2,x3) fKLQ( K12, L12, Q12, x1, x2, x3 );\nh2 = fimplicit3(f12,[xmin xmax ymin ymax zmin zmax]);\nf23 = @(x1,x2,x3) fKLQ( K23, L23, Q23, x1, x2, x3 );\nh3 = fimplicit3(f23,[xmin xmax ymin ymax zmin zmax]);\nf13 = @(x1,x2,x3) fKLQ( K13, L13, Q13, x1, x2, x3 );\nh4 = fimplicit3(f13,[xmin xmax ymin ymax zmin zmax]);\n\nfunction f = fKLQ( K, L, Q, x1, x2, x3 )\n x = [x1(:),x2(:),x3(:)];\n n = numel(x1);\n if n == 1\n x = x.';\n end\n f = zeros(1,n);\n for ii = 1:n\n f(ii) = K + L.'*x(:,ii) + x(:,ii).'*Q*x(:,ii);\n end\nend\n</code></pre>\n<p>The <code>x1,x2,x3</code> inputs for <code>fimplicit</code> are either row vectors or scalars, so you have to handle that when forming <code>x</code> correctly - there might be a simpler way to do that than what I've shown but I believe it at least works like this.</p>\n<p>The output divides your clusters as shown.</p>\n<p><a href="https://i.sstatic.net/Mbk16gpB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Mbk16gpB.png" alt="plot" /></a></p>\n<p>Note: there are still some warnings about vectorisation here, I believe that's something to do with how I've written the matrix multiplication, with MATLAB warning that the evaluation output might not be as expected. You could avoid this by explicitly adding each coefficient, or maybe there's some other formulation, but in the meantime I think it's benign.</p>\n"^^ . "0"^^ . "1"^^ . . "3"^^ . . "0"^^ . . "0"^^ . . . . . . . . . "<p>I am writing a MATLAB program, (1) containing main loop and (2) using keyboard. However, they are don’t work simultaneously.</p>\n<ol>\n<li>Code</li>\n</ol>\n<pre><code>function p\n \nfig=figure(1);\nset(fig,'KeyPressFcn',@myfun);\n \n% plot(1,1) %2\n% drawnow %2\n \nex=0;\n% while ~ex %1\n% % ... %1\n% end %1\n \n function myfun(~,event)\n disp(event.Key);\n end\n \nend\n</code></pre>\n<p>works: Figure 1 window opens, and all keystrokes appear in command window.</p>\n<ol start="2">\n<li><p>Open lines marked with %1, i.e. add the main loop, and start the script execution.\nFigure 1 window doesn’t open.\nStopping the script execution with Ctrl-C, Figure 1 opens and keystrokes begin to appear in command window.</p>\n</li>\n<li><p>Now open lines marked with %2 and start. The Figure 1 window opens, but there is no visible reaction to keystrokes.\nStopping the script execution with Ctrl-C, all keystrokes that occurred between startup and Ctrl-C dump out into the command window.</p>\n</li>\n</ol>\n<p>How can I make main loop and keystrokes response to work simultaneously?</p>\n"^^ . "0"^^ . . . . "opencv"^^ . . . . . . . "0"^^ . "1"^^ . . . "struct"^^ . . "0"^^ . . "0"^^ . . "2"^^ . . "0"^^ . . . . "vectorization"^^ . . . "0"^^ . "How have you configured your Python environment in MATLAB? Is `ExecutionMode` in or out of process? https://www.mathworks.com/help/matlab/ref/pyenv.html — The `'OutOfProcess'` mode is designed for cases like this, where there’s likely a conflict in a library. You’re not passing data from the one to the other anyway, so there’s no advantage to in process execution."^^ . . . "com"^^ . . . . . . . "0"^^ . . "Thank you for the comment Luis mendo.. Nevertheless.. I suppose something went wrong..I got this error message: \n\nDB =\n\n 3x5 cell array\n {1x1 cell} ...\n\nIndex in position 1 exceeds array bounds. Index must not exceed 1.\nError in untitled (line 8)\nresult = sum(cell2mat(cellfun(@(x) x, DB)), 1)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n(I didn't check the time that it take yet).\nThank you for your reply. JJVVE"^^ . . . . . "Previous issue with 3d discriminant and solution: https://stackoverflow.com/questions/79271633/plotting-outputs-of-3d-quadratic-discriminant-analysis-in-matlab/79284721?noredirect=1#comment139816256_79284721"^^ . "Since the null space has dimension 1 (rank+nullity=number of columns and the rank of that matrix is definitely 3) any basis vector for that null space must be a constant multiple of another. Unfortunately that constant is a complex number, so not always easy to see. When, as here, the null space has dimension 1, the components of vectors produced by either software should be in constant ratio. In fact, for this particular form of matrix, the first three components of those vectors should be complex proportional to the last column of A."^^ . "0"^^ . . . . "0"^^ . . . "1"^^ . "0"^^ . . . . . . . "0"^^ . "cvxr"^^ . . . . . "0"^^ . "Is cv.findEssentialMat using matlab in someway?"^^ . . . "0"^^ . . "0"^^ . . . "It would help (us and you) if you simplified the problem and tested your MATLAB code with specific inputs in isolation, within the MATLAB IDE so you can add breakpoints, debug, and see full error traces. That would likely address point **1.** where your code isn't behaving how you expect. For **2.** Presumably `VI` is within `spm_jobman` but we can't see that here, the previous point would help in debugging this too. By the time we're at **3.** this question is too broad, again we can't debug it here, I'd advise you run one of the problematic inputs within the MATLAB IDE and debug"^^ . . . . "Nothing comes in the logs it just crashes but when I trued to reduce the sample size it worked just fine but got another error where the results pointers are not aligned"^^ . . "3"^^ . "0"^^ . "0"^^ . "<p>I've got a program that computes the null space of a matrix using scipy null_space. My code works absolutely perfectly when the matrix is real but seems to contradict results in MATLAB for complex matrices.</p>\n<p>For instance,</p>\n<pre><code>[[ 1. +0.j 0. +0.j 0. +0.j -0.28867513+0.5j]\n [ 0. +0.j 1. +0.j 0. +0.j -0.28867513-0.5j]\n [ 0. +0.j 0. +0.j 1. +0.j 0.57735027-0.j ]]\n</code></pre>\n<p>when plugged into scipy.linalg.null_space gives,</p>\n<pre><code>[[ 0.24235958-0.32852474j]\n [ 0.16333098+0.37415192j]\n [-0.40569056-0.04562718j]\n [ 0.70267665+0.0790286j ]]\n</code></pre>\n<p>The exact same matrix in MATLAB gives,</p>\n<pre><code>0.2235 - 0.3134i\n0.1596 + 0.3502i\n-0.4151 + 0.2949i\n0.6636 + 0.0639i\n</code></pre>\n<p>These are clearly not the same up to scaling, so what's happening ? Is scipy just not very accurate for complex matrices or am I doing something wrong ?? Again my code works absolutely perfectly when the matrices happen to be real. Thanks in advance !</p>\n"^^ . "0"^^ . "1"^^ . "1"^^ . "3"^^ . . . "0"^^ . . "Because you did not specify the word boundary, `'([a-zA-Z_]\\w*)\\>(?!\\s*\\()'`. The ``\\>`` is the boundary for the end of the word."^^ . . . "<p>I'm trying to use vlfeat to calculate MSER features and then input them as keypoints to perform SIFT description. My issue is, no matter how many keypoints, matlab crashes, I can't really understand why and I'm too new in this field to know more, any ideas?</p>\n<pre><code>% Clear workspace and initialize\nclear;\nclc;\nclose all;\n\n% Step 1: Load the image\nimg = imread('footwear.jpg'); % Replace with your image file name\nif size(img, 3) == 3\n grayImg = rgb2gray(img); % Convert to grayscale if it's an RGB image\nelse\n grayImg = img;\nend\n\n% Step 2: Perform MSER detection\nmserRegions = detectMSERFeatures(grayImg);\n\n% Extract MSER locations and scales\nmserLocations = mserRegions.Location;\nmserScales = mserRegions.Axes; % Major and minor axes of MSER ellipses\n\n% Compute approximate scales using the geometric mean of axes\nnumRegions = size(mserLocations, 1);\nscales = sqrt(prod(mserScales, 2)); % Geometric mean of axes\norientations = zeros(numRegions, 1); % Default orientation (set to 0)\n\n% Limit the number of keypoints (to prevent excessive memory usage)\nmaxKeypoints = min(500, numRegions); % Use at most 500 keypoints\nmserLocations = mserLocations(1:maxKeypoints, :);\nscales = scales(1:maxKeypoints);\norientations = orientations(1:maxKeypoints);\n\n% Construct frames matrix for VLFeat\nframes = [mserLocations(:, 1)'; mserLocations(:, 2)'; scales'; orientations'];\n\n% Step 3: Set up VLFeat\nrun('C:\\Users\\user\\Desktop\\ERGASIA\\vlfeat-0.9.21\\toolbox\\vl_setup'); % Replace with your VLFeat path\n\n% Step 4: Compute SIFT descriptors using VLFeat\ntry\n [~, descriptors] = vl_sift(single(grayImg), 'frames', frames);\ncatch ME\n fprintf('Error during SIFT computation: %s\\n', ME.message);\n return;\nend\n\n% Step 5: Visualize MSER regions and SIFT keypoints\nfigure;\nimshow(grayImg);\nhold on;\n\n% Plot MSER regions\nplot(mserRegions, 'showPixelList', false, 'showEllipses', true);\n\n% Plot SIFT keypoints\nvl_plotframe(frames);\n\ntitle('MSER Regions and SIFT Keypoints');\nhold off;\n\n% Display some statistics\nfprintf('Number of MSER Regions Detected: %d\\n', numRegions);\nfprintf('Number of Keypoints Used: %d\\n', maxKeypoints);\nfprintf('Size of Descriptors: [%d x %d]\\n', size(descriptors));\n</code></pre>\n"^^ . . . . . . "0"^^ . . . . . . "@CrisLuengo, thank you, I will pay attention to the details you have made."^^ . "<p>You can use the same logic as in the code that you use for one constraint. It is better to define an indexing variable, so you can use it in both sides of the assignment statement:</p>\n<pre><code>ind = (B==1) &amp; (A&gt;=7) &amp; (A&lt;=9); % logical index of elements to be modified\nA(ind) = A(ind) + some_number;\n</code></pre>\n"^^ . . "How to Highlight the Difference Between Two Bar Charts in MATLAB?"^^ . . . . . . . "0"^^ . . . . "<p>Try modify your dart code like that:</p>\n<pre><code>Pointer&lt;Double&gt; listToPointerDouble(List&lt;double&gt; sample) {\n final Pointer&lt;Double&gt; pointer =\n calloc.allocate&lt;Double&gt;(sample.length, alignment: 8);\n final nativeSamples = pointer.asTypedList(sample.length);\n nativeSamples.setAll(0, sample);\n return pointer.cast&lt;Double&gt;();\n}\n</code></pre>\n<p>Don`t forget to free your memory after is unnecessary.</p>\n<pre><code>calloc.free(pointer);\n</code></pre>\n"^^ . . "0"^^ . . . "0"^^ . . . . . . . "0"^^ . . . "1"^^ . "linear-interpolation"^^ . "Programmatically find the "Saved in Simulink version" for a .sldd object in Matlab/Simulink"^^ . . . . . . . . "1"^^ . "0"^^ . "neural-network"^^ . "There is also an "export code to mfile" option within the SaveAs menu which makes @il_raffa's suggestion a bit simpler if OP can re-open the app in the original version of their app"^^ . "2"^^ . . "Ah ok thanks. I think they like to have questions answered. If you put this in an answer I'll accept it."^^ . "I would think about whether this is the best way to present your data, if that difference is what you want the reader to notice."^^ . . "1"^^ . . "0"^^ . "Access to directory is tricky in Matlab"^^ . . . "1"^^ . . "0"^^ . "<p>Due to certain dependancies I have to downgrade my Matlab from 2024b to 2022b. I am working in a conda environment with python 3.9.12</p>\n<p>After trying to install matlabengine with:</p>\n<pre><code>cd &quot;matlabroot/extern/engines/python&quot;\npython setup.py install\n</code></pre>\n<p>I get this error:</p>\n<pre><code>/opt/anaconda3/envs/myenv/lib/python3.9/site-packages/setuptools/_distutils/cmd.py:66: SetuptoolsDeprecationWarning: setup.py install is deprecated.\n!!\n\n ********************************************************************************\n Please avoid running ``setup.py`` directly.\n Instead, use pypa/build, pypa/installer or other\n standards-based tools.\n\n See https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html for details.\n ********************************************************************************\n\n!!\n self.initialize_options()\n/opt/anaconda3/envs/myenv/lib/python3.9/site-packages/setuptools/_distutils/cmd.py:66: EasyInstallDeprecationWarning: easy_install command is deprecated.\n!!\n\n ********************************************************************************\n Please avoid running ``setup.py`` and ``easy_install``.\n Instead, use pypa/build, pypa/installer or other\n standards-based tools.\n\n See https://github.com/pypa/setuptools/issues/917 for details.\n ********************************************************************************\n\n!!\n self.initialize_options()\n/opt/anaconda3/envs/myenv/lib/python3.9/site-packages/setuptools/command/sdist.py:122: SetuptoolsDeprecationWarning: `build_py` command does not inherit from setuptools' `build_py`.\n!!\n\n ********************************************************************************\n Custom 'build_py' does not implement 'get_data_files_without_manifest'.\n Please extend command classes from setuptools instead of distutils.\n\n See https://peps.python.org/pep-0632/ for details.\n ********************************************************************************\n\n!!\n self._add_data_files(self._safe_data_files(build_py))\nerror: The installation of MATLAB is corrupted. Please reinstall MATLAB or contact Technical Support for assistance.\n</code></pre>\n<p>which didn't appear when I had 2024b.</p>\n<p>I have tried reinstalling 2022b and got the same error. I can't install outside the environment as I have python 3.12 which isn't supported by MATLAB 2022b.</p>\n"^^ . . . . "You cannot do that. You can only use `system` to run a Python script (the function just says “run this in a terminal”). Interaction between Python and MATLAB needs to go through `pyenv` and the like."^^ . . . . "There is another little nuisance. When Alt key is pressed, control is transferred to the Figure 1 menu and subsequent keystroke is processed not by my code, but by the menu. For example, if Alt was pressed (and released) and than I press ‘H’ key the Help submenu opens instead of my assignment for ‘H’. Is it possible to avoid?"^^ . "0"^^ . "Maximum number of function evaluations has been exceeded - increase MaxFunEvals option"^^ . "@Wolfie Good idea, thanks! Edited into the answer"^^ . . . . . "1"^^ . . . . . . . . . . "@Irreducible if you write `the [dsp.se] SE` in a comment, it shows up as "the [dsp.se] SE""^^ . . "0"^^ . . . . "0"^^ . . . . . . . . . . . . "1"^^ . . . "Did you look at intermediate values? `zx`, your zero crossings, is an empty array. Then `per` is NaN, and with a NaN initialization value you will never find a solution."^^ . . "2"^^ . "Thanks for doing that - it does seem to be the particular cause of the OP’s problem."^^ . . . "0"^^ . . . . . "3"^^ . "0"^^ . "0"^^ . "0"^^ . . "1"^^ . . . "doxygen"^^ . . "0"^^ . . . "<p>slprj is a folder created by Simulink for storing model artifacts. You can create src and include directories for your own files.</p>\n<p>include directory typically contains header files for declarations.</p>\n<p>tmwtypes.h is part of MATLAB. You do not need to include it.</p>\n"^^ . . . . "0"^^ . . . "0"^^ . . . "0"^^ . . . "0"^^ . . . . . . . . "1"^^ . "2"^^ . . "1"^^ . . . . "2"^^ . . . "@Davide you could probably do something with `DT = delaunay( x, y ); trisurf( DT, x, y, z );` and instead of using `x` and `y` from a linearly spaced mesh you create a mesh from `p2 = interp1( 1:size(p,1), p, linspace(1,size(p,1),100) );` to create a finer-spaced set of points around the perimeter and create a finer mesh from the unique values in `p2`. The Delaunay triangulation should mean you can use a much lower resolution but the polygon edges can be included as triangular edges in the mesh, sorry this isn't a full solution but maybe a nudge in the right direction."^^ . . . "how to sum cells/ struct in matlab"^^ . . . "Identifying variables outside of function calls"^^ . "<p>I am working on a MATLAB project where I have two sets of data:</p>\n<p>1- &quot;<strong>No Reflection</strong>&quot;: Represents baseline coverage area values.\n2- &quot;<strong>With Reflection</strong>&quot;: Represents coverage area values with an additional reflection effect.</p>\n<p>I am plotting these two datasets as a grouped bar chart and I want to highlight the difference caused by the reflection. Specifically, I need the section of each bar corresponding to the difference (reflection effect) to be highlighted in a different color on top of the &quot;No Reflection&quot; bars.</p>\n<p><a href="https://i.sstatic.net/f5WSyB16.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/f5WSyB16.png" alt="enter image description here" /></a></p>\n<p><strong>Example:</strong>\nFor instance, if:</p>\n<ul>\n<li>&quot;No Reflection&quot; value for the first bar (QAM = 16) is 120 m².</li>\n<li>&quot;With Reflection&quot; value for the same bar is 160 m².</li>\n</ul>\n<p>I want to:</p>\n<p>1- Plot a bar representing 120 m² (base value for &quot;No Reflection&quot;).</p>\n<p>2- Highlight the difference (160 - 120 = 40 m²) on top of the blue bar in red (highlight for the reflection effect).</p>\n<p>I want to apply this on all the bars on the image that is on the right side. Any assistance, please?</p>\n<p>This is my code:</p>\n<pre><code>close all;\nclear variables;\nclc;\n\nQAM = [16, 32, 64, 128, 256, 512, 1024];\n\n%% m_CAP modulation\n\n% Beamsteering without reflection\nVEC_Beam_no_reflection_mCAP = [\n 117.5491 75.1933 53.5396 38.3105 23.0815 13.5634 6.9007; % Theta = 10\n 118.2629 76.1452 54.0155 39.0244 23.0815 13.5634 6.9007; % Theta = 30\n 118.2629 76.3831 54.0155 39.5003 22.8435 13.5634 6.9007; % Theta = 45\n 118.2629 76.6211 54.2534 39.5003 22.8435 13.5634 6.9007 % Theta = 60\n];\n\n% Beamsteering with reflection\nVEC_Beam_reflection_mCAP = [\n 121.3563 77.0970 54.7293 39.7383 22.8435 13.5634 6.9007; % Theta = 10\n 141.1065 88.7567 61.6300 42.5937 24.2713 14.5152 7.8525; % Theta = 30\n 153.7180 95.6573 67.8168 45.6871 26.6508 14.5152 8.8043; % Theta = 45\n 160.3807 100.6544 69.7204 50.4462 28.7924 16.4188 8.8043 % Theta = 60\n];\n\n%% DCO-OFDM modulation\n\n% Beamsteering without reflection\nVEC_Beam_no_reflection_OFDM = [\n 91.3742 59.7264 42.1178 28.7924 16.4188 8.8043 4.9970; % Theta = 10\n 95.4194 58.2986 34.7412 25.9369 16.4188 10.7079 4.9970; % Theta = 30\n 89.4706 59.4884 44.4973 24.7472 16.4188 8.8043 4.9970; % Theta = 45\n 83.5217 69.4825 40.2142 28.7924 16.4188 10.7079 4.9970 % Theta = 60\n];\n\n% Beamsteering with reflection\nVEC_Beam_reflection_OFDM = [\n 94.7055 61.8679 42.1178 28.7924 16.4188 8.8043 4.9970; % Theta = 10\n 113.9798 69.7204 42.1178 28.7924 16.4188 10.7079 4.9970; % Theta = 30\n 115.6454 74.9554 55.6811 28.7924 16.4188 9.7561 4.9970; % Theta = 45\n 114.4557 88.7567 50.6841 34.5033 21.1779 11.6597 4.9970 % Theta = 60\n];\n\n%% Combine Data for Bar Chart\nangles = [10, 30, 45, 60];\ndata_no_reflection = [VEC_Beam_no_reflection_mCAP; VEC_Beam_no_reflection_OFDM];\ndata_with_reflection = [VEC_Beam_reflection_mCAP; VEC_Beam_reflection_OFDM];\n\n% Generate gradient colors for m-CAP (blue) and DCO-OFDM (green)\nmCAP_blue_gradient = [linspace(0.8, 0.1, 4)', linspace(0.9, 0.2, 4)', linspace(1.0, 0.3, 4)']; % Light to dark blue\nDCO_green_gradient = [linspace(0.7, 0.1, 4)', linspace(0.9, 0.4, 4)', linspace(0.6, 0.2, 4)']; % Light to dark green\n\n% Combine colors\ncustom_colors = [mCAP_blue_gradient; DCO_green_gradient];\n\n% Plot for No Reflection\nfigure('Position', [100, 100, 800, 600]);\nb1 = bar(data_no_reflection', 'grouped');\nfor k = 1:length(b1)\n b1(k).FaceColor = 'flat';\n b1(k).CData = repmat(custom_colors(k, :), size(b1(k).CData, 1), 1);\nend\nxticks(1:length(QAM));\nxticklabels(string(QAM));\nxlabel('QAM Order, M');\nylabel('Coverage Area (m²)');\ntitle({'Coverage Area Without Reflection', 'm-CAP and DCO-OFDM'});\nlegend([&quot;m-CAP \\Phi_{1/2}=10°&quot;, &quot;m-CAP \\Phi_{1/2}=30°&quot;, &quot;m-CAP \\Phi_{1/2}=45°&quot;, &quot;m-CAP \\Phi_{1/2}=60°&quot;, ...\n &quot;DCO-OFDM \\Phi_{1/2}=10°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=30°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=45°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=60°&quot;], ...\n 'Location', 'Best');\ngrid on;\n\n% Plot for With Reflection\nfigure('Position', [100, 100, 800, 600]);\nb2 = bar(data_with_reflection', 'grouped');\nfor k = 1:length(b2)\n b2(k).FaceColor = 'flat';\n b2(k).CData = repmat(custom_colors(k, :), size(b2(k).CData, 1), 1);\nend\nxticks(1:length(QAM));\nxticklabels(string(QAM));\nxlabel('QAM Order, M');\nylabel('Coverage Area (m²)');\ntitle({'Coverage Area With Reflection', 'm-CAP and DCO-OFDM'});\nlegend([&quot;m-CAP \\Phi_{1/2}=10°&quot;, &quot;m-CAP \\Phi_{1/2}=30°&quot;, &quot;m-CAP \\Phi_{1/2}=45°&quot;, &quot;m-CAP \\Phi_{1/2}=60°&quot;, ...\n &quot;DCO-OFDM \\Phi_{1/2}=10°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=30°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=45°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=60°&quot;], ...\n 'Location', 'Best');\ngrid on;\n</code></pre>\n"^^ . . . . . . . . . "cmd"^^ . . . . "1"^^ . . . . "0"^^ . "0"^^ . . . . "One dimensional quadratic discriminant analysis in matlab"^^ . "@Compo Thanks for the clarifying example with the double quotes. Why is it best practice to use the double quotes? Just curious."^^ . "5"^^ . . "0"^^ . "Loop and keyboard don’t work simultaneously"^^ . "1"^^ . . "1"^^ . . . . . . "I would like this because if I take, supose, `n=50` points, then near the edges the plot loses its smoothness, and I was thinking that by considering also the points on the edges it's possible to smooth it."^^ . . . . "0"^^ . . "0"^^ . . . "What is the green? Is it something given, or something to be calculated?"^^ . "2"^^ . "How do I update pixelClassificationLayer() to a custom loss function?"^^ . . . "0"^^ . . . . . . . . . "3"^^ . "Sum row values when first column data is equal"^^ . "1"^^ . . . "1"^^ . . . "0"^^ . . . . . "Could you show how Scilab works here?"^^ . . "0"^^ . . . . . . . "<pre><code>&gt;&gt; table2array(removevars(groupsummary(array2table(c), &quot;c1&quot;,&quot;sum&quot;),'GroupCount'))\n\nans =\n\n 11 4\n 12 5\n 13 23\n\n</code></pre>\n<p>or</p>\n<pre><code>&gt;&gt; [unique(c(:,1)),accumarray(findgroups(c(:,1)),c(:,2))]\n\nans =\n\n 11 4\n 12 5\n 13 23\n</code></pre>\n"^^ . . "Solving differential equations with ode solvers and finite difference in Matlab"^^ . . "1"^^ . "regex"^^ . "0"^^ . . . "I have the following error while designing a basic charge controller using PV array instead of Constant dc source"^^ . . "0"^^ . "dot"^^ . "0"^^ . "3"^^ . "Application Compiler: Not able to run this app to package Code and create an Executable in Matlab"^^ . . "0"^^ . . "0"^^ . . . "8"^^ . "python"^^ . "0"^^ . . . "<p>The <a href="https://uk.mathworks.com/help/simulink/slref/mathfunction.html" rel="nofollow noreferrer">math function block</a> can be set to calculate <code>exp(u) = e^u</code>, you can just use a <code>gain</code> block to first multiply your input by 2, then use the math block.</p>\n<p><a href="https://i.sstatic.net/2yduSIM6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2yduSIM6.png" alt="block diagram" /></a></p>\n<p>If you really want this in a specific, single &quot;block&quot; then you can create a subsystem from the above blocks (<kbd>CTRL</kbd>+<kbd>G</kbd> or via the context menu when highlighted), then right-click &gt; Mask &gt; Edit Icon Image... and select your image. You could make this a mask such that you can configure the gain, or add it to a custom library so you can reuse it:</p>\n<p><a href="https://i.sstatic.net/pIFl7Efg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pIFl7Efg.png" alt="subsystem with image" /></a></p>\n"^^ . "markov-chains"^^ . . . "montecarlo"^^ . . "How to insert NULL values into a SQLite database table using MATLAB?"^^ . . "This question looks very similar to https://stackoverflow.com/q/78576265/16582 The big difference is that your segments are variable sizes. Given that you allow different segment sizes, what exactly are you trying to optimize? The number of segments, or something else? FYI here is the application I developed to solve the problem witch a fixed segment size https://github.com/JamesBremner/Mapify"^^ . . "1"^^ . . "0"^^ . . . . . "It would be helpful if you stripped out the app bits of this code and just presented the standalone calculation function with example input values (which you're currently inputting via the app). Aside from that, the `while true` is very suspect when you're reporting your code is hanging, have you tried adding a breakpoint here to debug what's happening? How about adding an iteration counter and erroring after some number of iterations?"^^ . "0"^^ . . . "5"^^ . "0"^^ . . . . . "1"^^ . "1"^^ . "@simon, c'est la vie, but that's teamwork :-)"^^ . . . "I don’t know if the answer below answers your question or not. Because it is unclear to me exactly what you are asking. If it does answer it, just give it the green tick mark and we can move on. Otherwise, please [edit] your post to include exactly what data structure you have and what you want to have. Preferably by including a bit of code that mocks up a representative example of the struct you currently have."^^ . . . "0"^^ . . . . . "python-3.x"^^ . "0"^^ . . "Thanks! Wow, that was simple. This is from timestamping the arrival of photons in two different telescopes pointed at the same star. Stellar Intensity Interferometry. We are looking for the near simultaneous arrival of two photons - one in each telescope. As the earth rotates and the star moves across the sky, the path differences from the star to each telescope changes. We have to offset this difference to find those that would have arrived simultaneously had the paths been identical. The actual numbers I add are in 1000s of picoseconds and channel 1 and 2 are scopes 1 and 2."^^ . "1"^^ . "0"^^ . . . . . "0"^^ . "1"^^ . "<p>it seems like .mlapp not compatiable or has changed since version 2023a and I am not sure what kind of promblem it is.</p>\n<p>.mlapp seems to be a Matlab-specific format, not a normal text format, which makes it impossible for me to copy it to other computers (running different versions of Matlab) at will.</p>\n<p>Is there any information about compatibility between APP designer versions? I cannot accept the incompatibility of &quot;source code (in binary format)&quot;.</p>\n<p><a href="https://i.sstatic.net/2f6b9ZXM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2f6b9ZXM.png" alt="enter image description here" /></a></p>\n"^^ . "0"^^ . . "0"^^ . . . . "<p>I am trying to simulate a specific block in Simulink using MATLAB, specifically the block represented by the expression e^(2s). I want to create this block visually in Simulink. I found an image online that shows how this block looks, and I would like to replicate it in my Simulink model. However, I’m not sure how to create this block effectively.</p>\n<p>I would appreciate guidance on the steps involved in creating this block, including any specific parameters or settings I should use.</p>\n<p><img src="https://i.sstatic.net/JpogW4y2.png" alt="this is image i WANT TO SIMULINK HO TO SIMULINK" /></p>\n"^^ . . "0"^^ . "<p>If you look closely, the second link you provide leads to the GitHub project <a href="https://amroamroamro.github.io/mexopencv/" rel="nofollow noreferrer"><code>mexopencv</code></a>. The corresponding project <em>provides MATLAB MEX functions that interface with hundreds of OpenCV APIs [and] is suitable for fast prototyping of OpenCV application in MATLAB, use of OpenCV as an external toolbox in MATLAB</em> (quote from the project's README). The first link you provide, which leads to the official OpenCV documentation, does not mention MATLAB.</p>\n<p>So, to make it clear: No, &quot;standard&quot; OpenCV does <em>not</em> use MATLAB in any way. It is the <code>mexopencv</code> project that you found, which provides bindings between OpenCV and MATLAB.</p>\n"^^ . "3"^^ . . . "state-space"^^ . . "cross-entropy"^^ . "How to divide a matrix in MATLAB into N^2 segments each with NxN elements?"^^ . "Have you checked the help of `ifft` (see [ifft](https://de.mathworks.com/help/matlab/ref/ifft.html)), there is a paragraph how to convert the single-sided spectrum into a two sided spectrum."^^ . "1"^^ . . "Using Doxygen `1.9.8` in the setup described [here](https://stackoverflow.com/questions/79385264/doxygen-cannot-see-m2cpp-filter-inside-of-container). And I have set `FILTER_SOURCE_FILES = NO`. Why do you mention this configuration? Are you proposing that I set it and `SOURCE_BROWSER` to `YES` and then inspect my filtered MATLAB code?"^^ . . . . . "3"^^ . "4"^^ . "@jeanjacquesvivde It works with `DB` as defined in your question; see [here](https://tio.run/##TcuxCoNAEITh/p5iSg8ssrsaI0EI4luIhcil0gSiBuHw2S@n22SqH4bvPSz914XQ1JWHb4lA3O04UkBZzFg56KpVgG5aJfjS7XeDY75lAvP5sIDVcQ5WxwVYHZeQfycEUScCUSc5RJ0UEHVSIosuQvNx8zouqDCvUzK4ceSpX854rq/kkWwWW4qmtjYFWWNC@AE)"^^ . "1"^^ . "Have you done what Cris suggested (i.e., verifying that the problem does not come from some code that you did not include in your question)? The code you posted cannot be the source of your problem, since it does the same thing for any `i` or `j` value"^^ . "0"^^ . . . "0"^^ . . . "Matlab crashes after using vl_sift function with MSER-detected keypoints"^^ . "1"^^ . "6"^^ . . "MATLAB error when running python code with pyrunfile"^^ . . . . . . "If nothing else works, you can recover the code from the .mlapp file, this way (**make a backup copy before**): change the extension of the file from `.mlapp` to `.zip` then unpack it in a folder. Explore the folders, you can find the MatLab code in the folder "matlab" (it is a xlm file, remove the uncecessary text), a picture of the GUI in the metadata folder and so on."^^ . "I think you could try. See this post ['setup.py install is deprecated' warning shows up every time I open a terminal in VSCode](https://stackoverflow.com/questions/73257839/setup-py-install-is-deprecated-warning-shows-up-every-time-i-open-a-terminal-i)"^^ . "Please add information via an [edit], not an an answer"^^ . . "0"^^ . . "0"^^ . . "Plotting a function inside a polygon in Matlab"^^ . . "2"^^ . . "I guess what you are missing is that you need to parse the command line arguments that you produce when you call `system()`. Python does not "magically" assign them to appropriate variables, but instead provides them via the `sys.argv` list. Try `import sys` and `print(sys.argv)` in your Python script to see if that gets you any further. Also see [here](https://docs.python.org/3/library/sys.html#sys.argv) for more doc on `sys.argv`."^^ . "1"^^ . "<p>You can use <code>structfun</code> to iterate over all of the fields in <code>OPC_UA</code>, and if the function you supply is just <code>@(x)x</code> then the node within that struct field will be returned. Since they're all scalar objects which can be concatenated into an array, they will be.</p>\n<p>Example setup:</p>\n<pre><code>OPC_UA = struct();\nOPC_UA.node1 = opcuanode(1, 'node1');\nOPC_UA.node2 = opcuanode(2, 'node2');\nOPC_UA.node3 = opcuanode(3, 'node3');\n</code></pre>\n<p>Using <code>structfun</code> to get all of the nodes into an array:</p>\n<pre><code>nodes = structfun( @(x)x, OPC_UA );\n</code></pre>\n<hr />\n<p>A more verbose way of doing this which would let you be selective about which fields of <code>OPC_UA</code> you use would be something like this, looping over the field names with dynamic <code>struct.(fieldname)</code> syntax:</p>\n<pre><code>fn = fieldnames( OPC_UA );\nnodes = opc.ua.Node.empty(0,1);\nfor i = 1:numel(fn)\n nodes(i,1) = OPC_UA.(fn{i});\nend\n</code></pre>\n"^^ . . . "0"^^ . "4"^^ . "how to operate on a Matlab vector A with a condition from vector B and a condition from the values of vector A"^^ . "function"^^ . "0"^^ . "<p>I'm using Doxygen to document a MATLAB codebase. Doxygen doesn't support MATLAB natively, so I am using the <code>m2cpp.pl</code> filter developed by <a href="https://uk.mathworks.com/matlabcentral/fileexchange/25925-using-doxygen-with-matlab" rel="nofollow noreferrer">Fabrice</a>. The filter is good, but not good enough for Doxygen to automatically generate callgraphs and collaboration graphs. I have considered a few solutions.</p>\n<p><strong>Improve the filter</strong></p>\n<p>The most 'proper' option but unfortunately not worth my time. The filter is written in Perl, which I have almost no experience with. Moreover, I am documenting a legacy codebase that is unlikely to change and will soon be re-written in Python.</p>\n<p><strong>Manually write DOT</strong></p>\n<p>Doxygen generates diagrams by writing files in the <a href="https://graphviz.org/doc/info/lang.html" rel="nofollow noreferrer">DOT language</a>, which are then rendered by Graphviz. I can add my own DOT files using the Doxygen <code>\\dotfile</code> command. The DOT language is quite simple, so I can define the call &amp; collaboration graphs that I want manually. However, this is tedious and leads to a lot of duplicated code.</p>\n<p><strong>Semi-manual approach</strong></p>\n<p>I was wondering if there is a middle-ground approach. I'm imagining a command that tells Doxygen which functions are called. For instance, in the code below I propose a new Doxygen command <code>\\calls</code>, which would manually tell Doxygen that <code>main()</code> calls <code>foo()</code> and <code>bar()</code>. I know this would be a DRY violation and therefore error prone, but it makes sense for my situation where I am documenting legacy code that is unlikely to change. Could I do this by making some simple edits to the filter?</p>\n<pre><code>%&gt; \\brief Demo function\nfunction result = foo()\n result = 1;\nend\n\n%&gt; \\brief Demo function\nfunction result = bar()\n result = 1;\nend\n\n%&gt; \\brief Demo function\n%&gt; \\calls foo, bar\nfunction result = main()\n var_1 = foo();\n var_2 = bar();\n result = var_1 + var_2;\nend\n</code></pre>\n<p><strong>External callgraph generator</strong></p>\n<p><a href="https://github.com/koknat/callGraph" rel="nofollow noreferrer">This callgraph generator</a> supports MATLAB and returns a DOT output, but I'm not sure how I would include it in my pipeline. I would have to automate some process where it generates dotfiles that are automatically pulled into Doxygen.</p>\n"^^ . . . . . . . . . "algorithm"^^ . "2"^^ . "3"^^ . . . ""recommended approaches" strays into asking for opinion-based answers or off-site resources, which are both off-topic. Could this be rephrased or put in terms of a specific example or problem you're facing implementing this so that we might be able to provide a concise, objective answer? It feels like you're talking about lots of things (what's running in MATLAB, how you're calling it from Python, ...) which might be irrelevant to what your core issue is, just running both MATLAB and Python on AWS? Have you tried to do either?"^^ . "0"^^ . . . . "0"^^ . "0"^^ . . . . . "0"^^ . "0"^^ . . . "I changed to \nxfill = [xaxis; flipud(xaxis)];\nyfill = [b; min(zaxis)*ones(size(b))];\npatch(xfill,yfill,'r');\nAnd it filled the area in between! Your comment gave me an idea. Thank you!"^^ . . "1"^^ . . . . . . "Ahh I see, thank you I missed those lines were different. Thank you!"^^ . "0"^^ . . . . . "5"^^ . "2"^^ . "You already got quite a few answers, but see if [this](https://stackoverflow.com/questions/20336288/for-loop-to-split-matrix-to-equal-sized-sub-matrices/20337173#20337173) helps"^^ . . . "0"^^ . . . . . "Thdnk you. But I've already tried this, and it only partially solves the problem. After pressing 'Alt', the first press of any letter goes nowhere (the second press gives the desired effect)."^^ . "0"^^ . . "executable"^^ . ".net"^^ . . . . . . . . . "I added an answer with the `im2col` approach, which is very easy but probably quite slow. Not sure if it's worth adding it to your benchmarking"^^ . "0"^^ . . . "Thanks but it still crashes"^^ . "0"^^ . "0"^^ . . . . "3"^^ . "“I can't get the quadratic (aka curved) boundaries to plot correctly.” Do you get an error message? or a boundary that is not what you expect? Is the plotting bad or is the discriminant itself bad? It would be much easier on us if you could remove things that are not relevant to the question from your code, see [mre]. There’s a lot there and it’s hard to know what your problem might be."^^ . . . "Is that your complete Python script? Then the error shouldn't be too surprising: The variables `target` and `originalPatient` have not been defined in the Python script. Where should they come from?"^^ . . . "Inverse Fast Fourier Transform from One-Sided Fourier Amplitude Spectra at Matlab"^^ . . . "0"^^ . . . "0"^^ . . "0"^^ . . "3"^^ . "Your question is incomplete. What was the output or error message? What is the expected result? Does the same error occur when applying the same methods to other, simpler ODE systems? You are transforming implicit differential equations into a vector field, is the occurrence of singularities possible or impossible?"^^ . . . "2"^^ . "The result of imwarp function IN MATLAB has horizontal stripes"^^ . "8"^^ . . . . . . . "1"^^ . . . . . "0"^^ . . . "loss-function"^^ . . "You need to add a breakpoint and step through your code, you must not be satisfying any of the `if` conditions so `YCOB` is never defined. Note that comparing doubles is always risky [see here](https://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab), you would be better using a tolerance around each value for `ZZ`"^^ . . . "<p>I think you just need to swap the order of concatenation for <code>yfill</code>, since you want <code>b</code> to align with <code>xaxis</code> in the original order and you can align <code>fliplr(xaxis)</code> with the min <code>zaxis</code> values.</p>\n<pre><code>xfill = [xaxis, fliplr(xaxis)];\nyfill = [b, min(zaxis)*ones(size(b))];\npatch(xfill,yfill,'r');\n</code></pre>\n<p>For some dummy example:</p>\n<pre><code>xaxis = linspace(0,10,7301);\nzaxis = rand( 1, 1376 ) - 1;\nb = sin( xaxis ) + xaxis;\nxfill = [xaxis, fliplr(xaxis)];\nyfill = [min(zaxis)*ones(size(b)), b];\npatch(xfill,yfill,'r');\n</code></pre>\n<p><a href="https://i.sstatic.net/19Lrs7r3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/19Lrs7r3.png" alt="patch example" /></a></p>\n"^^ . . . "@BillBokeey A lot of computation on the files in the subfolders of rank_1_dirs"^^ . "1"^^ . . "Note that variable names starting with an underscore are not valid, but this looks like it allows them."^^ . "0"^^ . "Well, yes, that is what you get when you interpolate pure noise. Interpolation is only valid when the signal is properly sampled. For that, you must have a band-limited signal. Noise is not band limited by definition. So you will never be able to interpolate it correctly. You can apply a smoothing filter before rotating to reduce this effect, but it will also make your image more blurry."^^ . . . "0"^^ . . "Thank you very much for you answer and the precious clarifications."^^ . "<p>The only way I figure is writing an M-file that builds all the comments.\nSomething like:</p>\n<pre class="lang-none prettyprint-override"><code>generator.m --&gt; pub.m --&gt; html\n(origin) (file to Publish) (Published web page)\n</code></pre>\n<p>My code example, <code>myOwnSolution.m</code> is:</p>\n<pre><code>% My own solution\nclc, clear, close all\nsyms s\n\nfprintf('I want to Publish a LaTeX Variable, randomly built.\\n');\nfprintf('Let''s say:\\n');\na = randi([2,7]);\nb = randi([2,7]);\nP = [1,a,b]; % Coeffs are randomly selected\nsymPol = poly2sym(P,s);\ndisp('A pretty view of P(s), in the Workspace:')\npretty(symPol);\nfprintf('\\n\\n')\n\nfileID = fopen('testPublishLaTeX.m','w');\n\nfprintf(fileID,'%%%% Publish a LaTeX variable\\n');\nfprintf(fileID,'%% This is a Publish file in Matlab\\n');\nfprintf(fileID,'%%%% First Section \\n');\nfprintf(fileID,'%% Publish a LaTeX variable in a text line: $P(s)=%s$\\n',latex(symPol));\nfprintf(fileID,'%%%% Second Section\\n');\nfprintf(fileID,'%% Publish a LaTeX variable and expression in a ordered list:\\n');\nfprintf(fileID,'%%\\n');\nfprintf(fileID,'%% # A LaTeX variable: $P(s)=%s$\\n',latex(symPol));\nfprintf(fileID,'%% # A LaTeX expression: $F(s)=\\\\alpha^2$\\n');\nfprintf(fileID,'%%%% Third Section\\n');\nfprintf(fileID,'%% Publish a LaTeX variable and expression in a unordered list:\\n');\nfprintf(fileID,'%%\\n');\nfprintf(fileID,'%% * A LaTeX variable: $P(s)=%s$\\n',latex(symPol));\nfprintf(fileID,'%% * A LaTeX expression: $F(s)=\\\\alpha^2$\\n');\nfprintf(fileID,'%%%% Fourth Section\\n');\nfprintf(fileID,'%% Publish a LaTeX variable and expression as lone expressions:\\n');\nfprintf(fileID,'%%\\n');\nfprintf(fileID,'%% $$P(s)=%s$$\\n',latex(symPol));\nfprintf(fileID,'%%\\n');\nfprintf(fileID,'%% $$F(s)=\\\\alpha^2$$\\n');\nfprintf(fileID,'%%%% Fifth Section\\n');\nfprintf(fileID,'%% Publish a LaTeX variable with (not in) HTML format:\\n');\nfprintf(fileID,'%%\\n');\nfprintf(fileID,'%% &lt;html&gt;\\n');\nfprintf(fileID,'%% &lt;div style=&quot;font-family:Georgia, serif; font-size:large;&quot;&gt;\\n');\nfprintf(fileID,'%% &lt;p&gt;This is my polynomial over s:&lt;/p&gt;\\n');\nfprintf(fileID,'%% &lt;/div&gt;\\n');\nfprintf(fileID,'%% &lt;/html&gt;\\n');\nfprintf(fileID,'%%\\n');\nfprintf(fileID,'%% $$P(s)=%s$$\\n',latex(symPol));\nfprintf(fileID,'%%\\n');\n\nfclose(fileID);\n\nmyDoc = publish(&quot;testPublishLaTeX.m&quot;,&quot;html&quot;);\n</code></pre>\n<p>Now, I can view in the browser the file <code>testPublishLaTeX.html</code>, just created with the <code>publish</code> command.</p>\n"^^ . "0"^^ . . "0"^^ . . . . "How to show ylabel fully?"^^ . "excel-formula"^^ . . "0"^^ . . "parameters"^^ . "0"^^ . . . . . . . . "Well, it seems that there is really no ideal solution to this problem. (·д·)"^^ . "0"^^ . "image-processing"^^ . "1"^^ . . "0"^^ . . . . "1"^^ . "1"^^ . "<p>Yes, there is a function specifically for Least-Squares method. It is called lsqcurvefit 3-rd output argument gives the residuals (errors) you want. See</p>\n<pre><code>help lsqcurvefit\n</code></pre>\n<p>In your case</p>\n<pre><code>initial_guess = [yr; per; -1; ym];\n[s, resnorm, residual] = lsqcurvefit(fit, initial_guess, x, y);\nplot(x, residual)\n</code></pre>\n<p>For the covariance I didn't find any method other then to compute it from the Jacobian (which is the 7th output arguments of lsqcurvefit):</p>\n<pre><code>[s, resnorm, residual, flag, output, lambda, jacobian] = lsqcurvefit(fit, initial_guess, x, y);\ncovariance = inv(jacobian' * jacobian) * resnorm / (length(y) - length(s));\n</code></pre>\n<p>Please check that this covariance formula is the one you want to compute.</p>\n<p>I hope this answers well.</p>\n"^^ . . "0"^^ . . "1"^^ . . . . . "1"^^ . . . "Ok, let me rephrase that. You are calling `fimplicit`. The docs say “fimplicit(f) plots the implicit function defined by f(x,y) = 0.” https://www.mathworks.com/help/matlab/ref/fimplicit.html Thus, you need to give it a function of x and y, and you need to use both variables if you don’t want to draw a vertical line. If you want to draw y=x^2, you pass it f(x,y)=x^2-y. If you have a function in the form f(x)=x^2, then you need to use a different function to plot it. Try for example `fplot`. https://www.mathworks.com/help/matlab/ref/fplot.html"^^ . . . "Please show us some code so we might be able to at least guess what's wrong, otherwise you've got a fairly detailed error message there, you likely need to improve the initial conditions going into the transfer function block because its initial derivative is not finite. You might find it helpful to read about creating a [mcve], or read [ask]"^^ . . "@lastchance yes, I updated the matrix through all examples, and re-ran the calculations"^^ . . "3"^^ . . . . . . . . "0"^^ . . . "0"^^ . "In a quick test I think using `cellfun` is slowing you down here, you could do something similar de-nesting with `{:}` and a `reshape` e.g. `sum(cell2mat(reshape([DB{:}],size(DB,1),[])), 1)`"^^ . . "vlfeat"^^ . . . . . "0"^^ . "0"^^ . . . . "0"^^ . "1"^^ . "1"^^ . . . "I already asked also to MATLAB support the same question. However, I must say that with MATLAB 2023b that used to work within a COM application. I tried to rollback to 2023b, but now I get the same error there too. So I guess I have something misconfigured."^^ . . . . . . . . . "<p>I have a Matlab file , which defines the variables in the Simulink model and then runs it. A Simulink.SimulationInput Object is used to this end.\nThe code i have used is a simple one.</p>\n<pre><code>simIn = Simulink.SimulationInput(&quot;Model&quot;);\nsimIn = simulink.compiler.configureForDeployment(simIn);\nsimIn = setModelParameter(simIn,RapidAcceleratorUpToDateCheck=&quot;on&quot;);\ninput1 = 1;\nsimIn = setVariable(simIn, &quot;input1&quot; , input1);\nsimOut = sim(simIn);\n</code></pre>\n<p>Running it in Matlab doesn't lead to any errors. However when i try to create an executable using Application Compiler, the following error message pops up</p>\n<p><em>Unrecognized function or variable 'input1'.\nError using buildRacTarget\nVariable 'input1' has been deleted from base workspace.</em></p>\n<p>The only way for me to prevent this error is to define the variable in the command window beforehand i.e before running the Application Compiler to create the executable. However this is not a usefull solution for my purposes.</p>\n<p>I have tried multiple approaches like:</p>\n<ol>\n<li>Using the evalin and assignin functions</li>\n<li>Using a 2nd Matlab script called initial.m, which defines the variable input1 and then passes it into a .m (which is a function script with the definition function model(input1) that defines the Simulink.SimulationInput object and runs the simulink model. Once again, this works perfectly in Matlab and Simulink but cannot be compiled into an executable.\nHowever, these approaches haven't worked.</li>\n</ol>\n<p>My question is , how can I fix it? Why is the variable defined in the .m file being deleted? Why doesn't this problem occur when executed in Matlab and Simulink?</p>\n<p>Hope you can help me out.\nHappy Holidays!</p>\n"^^ . . . . . . "3"^^ . . . . "I edited the comment. The word boundaries just look different there."^^ . . . "fill"^^ . "-2"^^ . . . "@flipSTAR Thanks a lot for the suggestion. I have posted the query on MATLAB Central also, hope I will get the solution from there. "^^ . . . . . . . "How to invoke a .bat file with elevated privileges from MATLAB"^^ . "0"^^ . . . "<p>Based on your code, you can achieve the same result with</p>\n<pre><code>result = sum(cell2mat(cellfun(@(x) x, DB)), 1);\n</code></pre>\n<p>or better (thanks to <a href="https://stackoverflow.com/users/3978545/wolfie">@Wolfie</a>)</p>\n<pre><code>result = sum(cell2mat(reshape([DB{:}], size(DB, 1), [])), 1);\n</code></pre>\n<p>This converts your cell array of cell arrays into a numerical 2D array, and then sums along the vertical dimension. However, this is not likely to be much faster than your current code.</p>\n<p>The issue with your approach is not the code, but the data type. If possible, you should define your <code>DB</code> variable directly as a numerical 2D array. That way the code would be simpler and faster: <code>result = sum(DB, 1);</code>. Normally, cell arrays in Matlab are only used if the contents are not homogenous in size or in type.</p>\n"^^ . . "Condition-based table column calculation"^^ . . "deep-learning"^^ . "-1"^^ . . . . "I am using 75.6.0. Should I downgrade?"^^ . . . "2"^^ . . . . . . . . "I don’t understand “I only want to use x1”. You are defining a function `f(x,y)`. You need to use both coordinates if you want to draw anything other than a vertical line. Also, your code in the question is ignoring the linear part, so you didn’t copy the example well enough."^^ . . . . "<p>I want to know if there are any ways to plot a given function with domain restricted to a polygon with given vertices, in Matlab.\nFor example, how can i plot the function\n<code>f =@(x,y) x.*y</code>\ninside the polygon whose vertices are given by <code>p1 = [0 0], p2 = [1 0], p3 = [2 2], p4 = [0 1]</code>?\nI know there exists the function <code>inpolygon</code> but I have no idea on how to use it to plot a function only inside the polygon.\nThanks in advance.</p>\n"^^ . . . "Heart rate detection with FMCW radar"^^ . . . . . "I both have a MATLAB licence and a Microsoft office license"^^ . "2"^^ . . "1"^^ . . "simulink"^^ . . . "0"^^ . . . . . . . "0"^^ . "Plotting outputs of 3D quadratic discriminant analysis in matlab"^^ . . . "<p>I tried to obtain the coefficients of B-spline matrix using the following code:</p>\n<pre><code>function C_matrix = calculateBsplineCoefficientMatrix(s)\n% Number of input samples\nN = length(s);\n% Construct Alpha Values (Used in the Recursive Calculation)\nalpha_values = zeros(1, 10);\nalpha_values(1) = -1/4;\nfor i = 2:10\n alpha_values(i) = -1 / (4 + alpha_values(i - 1));\nend\nalpha = alpha_values(end);\nb_i = -alpha / (1 - alpha^2);\n% Construct Forward Recursion Matrix (C_plus)\nC_plus = zeros(N, N); % Matrix to store forward recursion values\nC_plus(:, 1) = 1; % Initialize first column as 1\nfor k = 2:N\n C_plus(k, :) = alpha * C_plus(k-1, :);\n C_plus(k, k) = 1; % Set diagonal values to 1 for recursion steps\nend\n% Construct Backward Recursion Matrix (C_minus)\nC_minus = zeros(N, N);\nI_N = eye(N); % Identity matrix of size NxN\nC_minus(N, :) = b_i * (2 * C_plus(N, :) - I_N(N, :));\nfor k = N-1:-1:1\n C_minus(k, :) = alpha * (C_minus(k+1, :) - C_plus(k, :));enter image description here\nC_matrix = 6 * C_minus;\nend\n</code></pre>\n<p>s here represents the signal or sequence basically this code is created from the paper FastO-line interpolation by Dooley in pdf document(1).</p>\n<pre><code>s = rand(1, 4);\nC_spline_matrix = calculateBsplineCoefficientMatrix(s);\ndisp('B-Spline Coefficients Matrix Form:');\ndisp(C_spline_matrix);\n</code></pre>\n<p>The Solution is B-Spline Coefficients Matrix Form:</p>\n<pre><code>1.7327 -0.4665 0.1333 -0.0333\n-0.4665 1.7410 -0.4974 0.1244\n0.1333 -0.4974 1.8564 -0.4641\n-0.0666 0.2487 -0.9282 1.7321\n</code></pre>\n<p>Then I tried to calculate its quasi diagonal matrix using the following code:</p>\n<pre><code>M = length(s); % Polynomial order or interpolation order\n% Compute Transformation Matrices\nT_mu = compute_TD(M); % Transformation matrix T_mu\nT_z = calculate_Tz(M); % Transformation matrix T_z\n% Ensure numerical stability\nT_mu_invT = inv(transpose(T_mu)); % Explicit inverse transpose of T_mu\nT_z_inv = inv(T_z); % Explicit inverse of T_z\n% Compute the quasi-diagonal matrix C_LCN\nC_LCN = T_mu_invT .*C_spline_matrix .* T_z_inv;\n% Display the final quasi-diagonal matrix\ndisp('Computed C_LCN Matrix:');\ndisp(C_LCN);\n</code></pre>\n<p>The solution of quasi diagonal matrix</p>\n<p>Computed C_LCN Matrix:</p>\n<pre><code>1.8384 0 0 0\n-0.5937 -2.4397 0 0\n0.1728 1.1772 0.8176 0\n-0.0168 -0.2263 -0.3135 -0.0388\n</code></pre>\n<p>The relevant functions are given below:</p>\n<pre><code>function Td1 = compute_Td1(M)\n% Create a matrix of binomial coefficients\n[I, J] = ndgrid(1:M, 1:M);\nbinomials = zeros(M, M);\nfor ii = 1:M\n for jj = 1:M\n if jj &lt;= ii\n binomials(ii, jj) = nchoosek(ii-1, jj-1);\n end\n end\nend\n% Compute powers and combine with binomial coefficients\npowers = ((- (M - 1) / 2) .^ (I - J)) .* (J &lt;= I);\nTd1 = binomials .* powers;\n% Debugging: Display Td1 matrix\ndisp('Td1 Matrix:');\ndisp(Td1);\nend\nfunction Td2 = compute_Td2(M)\n% Compute the Td2 matrix\nTd2 = eye(M+1);\nfor n = 2:M+1\n for k = 2:n-1\n Td2(n, k) = Td2(n-1, k-1) - (n-2) * Td2(n-1, k);\n end\nend\nTd2 = Td2(2:M+1, 2:M+1);\n% Debugging: Display Td2 matrix\ndisp('Td2 Matrix:');\ndisp(Td2);\nend\nfunction TD = compute_TD(M)\nTd1 = compute_Td1(M);\nTd2 = compute_Td2(M);\n% Compute TD\nTD = Td1 * Td2;\n% Force symmetry in TD\nTD = (TD + TD') / 2;\n% Regularization for numerical stability\nTD = TD + 1e-8 * eye(size(TD));\n% Debugging: Display TD matrix\ndisp('Symmetrized TD Matrix:');\ndisp(TD);\nend\nfunction Tz = calculate_Tz(M)\n% Generate the Tz transformation matrix for Newton interpolation\nTz = zeros(M, M);\nfor i = 1:M\n for j = 1:i\n Tz(i, j) = nchoosek(i-1, j-1) * (-1)^(j+1);\n end\nend\n% Regularization for numerical stability\nTz = Tz + 1e-8 * eye(size(Tz));\n% Debugging: Display Tz matrix\ndisp('Tz Matrix:');\ndisp(Tz);\nend\n</code></pre>\n<p>The problem is the it does not match the values as solved in the paper Electronic letters.</p>\n<p>The solutions provided are:</p>\n<p><img src="https://i.sstatic.net/Wxe8ICfw.png" alt="enter image description here" /></p>\n<p><img src="https://i.sstatic.net/wjZirxuY.png" alt="enter image description here" /></p>\n<p>Lamb, David, Luiz FO Chamon, and Vítor Heloiz Nascimento. &quot;Efficient filtering structure for spline interpolation and decimation.&quot; <em>Electronics letters</em> 52.1 (2016): 39-41.</p>\n<p>Dooley, S., Stewart, R., and Durrani, T.: ‘Fast on-line B-splineinterpolation’, Electron. Lett., 1999, 35, (14), pp. 1130–1131</p>\n<p>Based on these papers solved the solutions by MATLAB please see whether the solution is correct or not?</p>\n"^^ . . "scipy"^^ . "0"^^ . . . "1"^^ . . "What is happening in your `browse_and_filter` function after the call to `disp({rank_1_dirs.name});`?"^^ . . "i actually used \npyenv("ExecutionMode","OutOfProcess");\nbut with or without it, nothing changes"^^ . . . . . "Is there a reason you want to use this approach over `FuncAnimation`?"^^ . "0"^^ . . "By the way, if Python is already loaded as in-process, you need to restart MATLAB to set the mode to out-of-process. AFAIK, you cannot switch from using Python in the one mode to the other within the same session."^^ . . . "your question is not clear. please explain little more"^^ . "3"^^ . . . "2"^^ . "discriminant"^^ . . . "4"^^ . . . . . "Start by using `traceback` to see what function is calling things like `.local` . Then set `debug` on all functions in the trace stack to see where you are passing data that is expected to have a `dimensions` attribute but doesn't."^^ . . . . "1"^^ . . . "1"^^ . "https://in.mathworks.com/matlabcentral/answers/2173431-how-to-programmatically-find-the-simulink-saved-version-for-a-sldd-dictionary-object?s_tid=mlc_ans_email_ques \n\nI have an answer from Anay for the above question. Need to check if it works."^^ . . . "0"^^ . . . "Glad, I could help. If there are angled paths, it is more complex indeed. But you already find significant angle changes, which could be indicators for your segment borders. ```polyshape``` let's you draw any kind of polygons by giving the endpoints in the right order. Maybe you'll ask a new question with such an example and we can try figuring it out."^^ . . . . . "@Compo I think you are indicating that `/C` is invoked and that the subsequent arguments passed to the function must in double quotes For example: cmd.exe /C "myBatchfile.bat". I think this is what `sprintf` does. That being said, `runas.exe` is new to me and seems to be a promising substitute for `cmd.exe`? https://ss64.com/nt/runas.html Not having any luck or maybe I missed something. Again, Thanks"^^ . . "0"^^ . "8"^^ . . "2"^^ . "0"^^ . "<p>I have two vectors. One with time information and one with channel information.<br />\nFor example, A has time values</p>\n<p>A = 1, 2.5, 2.7, 3, 4, 5, 6, 7, 8, 9, 10</p>\n<p>and B has channel values</p>\n<p>B = 1, 1, 2, 2, 2, 1, 2, 1, 2, 1, 1</p>\n<p>I wish to add a number to the elements of array A, only when array B == 1 and only when the value of those elements in array A are between 7 and 9 for example (A &gt;=7 &amp; A &lt;=9).</p>\n<p>I know how to do it for one constraint, but not for the second one.\nFor one constraint I would use</p>\n<p>A(B==1)=A(B==1) + &quot;some number&quot;</p>\n<p>I need to do this because the number I add will change depending upon the values in array A.\nI will eventually need to add numbers to every value in A if it is a channel 1 value.\nMy arrays are moderately large - 10^8 elements, but I only need to use about 50 ranges in array A. The values are monotonically increasing, but not by regular amounts.</p>\n<p>If I can do it for one range, I don't mind looping on the other ranges.</p>\n"^^ . . "0"^^ . . . "database"^^ . "1"^^ . . "differential-equations"^^ . "0"^^ . . . . . "<p>Maybe you can try</p>\n<pre><code>table2cell(varfun(@(x) sum(cell2mat(x),1),cell2table(DB)))\n</code></pre>\n<p>and you will obtain the result presented like</p>\n<pre><code> 1×5 cell array\n\n {[63 66]} {[69 72]} {[75 78]} {[81 84]} {[87 90]}\n</code></pre>\n"^^ . . "Does your shown `cmd.exe` command use either `/C` or `/K`? Even if you aren't specifying one, `/C` is default. Therefore, what I've told you is the correct syntax for what you've shown in your question, not an answer to your question. Of course, I'd want to know if you've considered not running `cmd.exe` directly, and perhaps using `runas.exe` to launch the batch file by name."^^ . . "0"^^ . "0"^^ . "Hi, when I changed the "while true" command line in the CALCULATEButtonPushed(app, event) function to " for i = 1:10000 ", the normal depth worked without any problems, but this time when I put "0" in the SIDEINCLINATION(ZZ) box in the ciritcal depth calculation, it gives the error "Unrecognized function or variable 'YCOB'. When I put "1", the code works without any problems. If you have any advice on this, I would like to know."^^ . "0"^^ . "Please re-read [mre]. You show us parts of the code that produce the problem, not the full code. You need to remove parts of your code you think are not relevant to the problem, then *run your code again* to verify it still causes your problem. *Then* you can post that reduced code here."^^ . "sqlite"^^ . "0"^^ . . "gazebo-simu"^^ . . . . "WIth regard to Doxygen versions, [corentinaltepe/doxygen](https://hub.docker.com/r/corentinaltepe/doxygen) runs version 1.9.5 and [hrektts/doxygen](https://hub.docker.com/r/hrektts/doxygen) runs version 1.8.17, so you're right that `PERL_PATH` is deprecated in both. I will remove it and the other deprecated configurations from my Doxyfile. However, I had thought it was relevant to `FILTER_PATTERNS` since the filter `m2cpp.pl` is written in Perl and therefore surely Doxygen needs access to a Perl installation to interpret it. I suppose it just uses the filter Shebang for this?"^^ . . . . . . . . . "<p>In Scilab, here is a solution without explicit <code>for</code> loop, provided that <code>c</code>'s first column is already sorted:</p>\n<pre><code>i = [c(2:$,1)~=c(1:$-1,1) ; %T];\ntmp = [0 ; cumsum(c,&quot;r&quot;)(i, 2)];\nres = [c(i,1), tmp(2:$)-tmp(1:$-1)]\n</code></pre>\n<p>yielding</p>\n<pre><code>--&gt; res = [c(i,1), tmp(2:$)-tmp(1:$-1)]\n res = [3x2 double]\n 11. 4. \n 12. 5. \n 13. 23.\n</code></pre>\n"^^ . . "2"^^ . "0"^^ . "0"^^ . . . . "0"^^ . . . . "Implementation of the parameters error in the Matlab program"^^ . "numpy"^^ . . "0"^^ . . "<p>You can combine <code>reshape</code> with <code>permute</code>, e.g. like so:</p>\n<pre><code>reshape(permute(reshape(M, N,N,N,N), [1,3, 2,4]), N,N, N*N)\n</code></pre>\n<p>The inner <code>reshape</code> has your intended &quot;cells&quot; split into dimensions 1 and 3, which <code>permute</code> shifts into dimensions 1 and 2. The outer <code>reshape</code> may be omitted, if you are ok with having a 4D matrix.</p>\n"^^ . . . . . . "0"^^ . . "0"^^ . "elastix-itk"^^ . "5"^^ . "Well the first thing you should be aware of, if running `cmd.exe` with `/C` or `/K` arguments is that all of those arguments should be enclosed within a single set of doublequotes. For example: ```%SystemRoot%\\System32\\cmd.exe /D /C "Arg1 "Arg 2" Arg3"```. _The outer quote pair are removed by `cmd.exe`_. You will note that nested doublequotes do not usually require additional escaping. It is however best practice to doublequote each individual argument, and where necessary, ask the called command or utility to handle any required removal of those doublequotes."^^ . "0"^^ . "2"^^ . . "<p>How to sum data in 2nd column for same values in column 1:</p>\n<pre><code>c = [11 1;\n 11 3;\n 12 5;\n 13 9;\n 13 11;\n 13 3]\n</code></pre>\n<p>expected result is:</p>\n<pre><code>r = [11 4;\n 12 5;\n 13 23]\n</code></pre>\n<p>I know how to manage this using a loop but is there another easier way? In Matlab the function <code>accumarray</code> would work but is there something similar in Scilab?</p>\n"^^ . "10"^^ . "<p>I was trying to fit a data set into a sinusoidal function with the code below:</p>\n<pre><code>data = importdata('analisipicco.txt') ; \nx = data(:,1) ; y = data(:,2) ; \nyu = max(y);\nyl = min(y);\nyr = (yu-yl); % Range of ‘y’\nyz = y-yu+(yr/2);\nzx = x(yz .* circshift(yz,[0 1]) &lt;= 0); % Find zero-crossings\nper = 2*mean(diff(zx)); % Estimate period\nym = mean(y); % Estimate offset\n\nfit = @(b,x) b(1).*(sin(2*pi*x./b(2) + 2*pi/b(3))) + b(4); % Function to fit\nfcn = @(b) sum((fit(b,x) - y).^2); % Least-Squares cost function\ns = fminsearch(fcn, [yr; per; -1; ym]) % Minimise Least-Squares\n\nxp = linspace(min(x),max(x));\n\nfigure(1)\nplot(x,y,'b', xp,fit(s,xp), 'r')\ngrid\n</code></pre>\n<p>Where the elements of output parameter vector, s ( b in the function ) are:</p>\n<p>s(1): sine wave amplitude (in units of y)</p>\n<p>s(2): period (in units of x)</p>\n<p>s(3): phase (phase is s(2)/(2*s(3)) in units of x)</p>\n<p>s(4): offset (in units of y)</p>\n<p>But when I run the code with my set of data the command window show this:</p>\n<pre><code>Maximum number of function evaluations has been exceeded\n - increase MaxFunEvals option.\n Current function value: NaN \ns =\n\n 1.0e+05 *\n\n 1.0466\n NaN\n -0.0000\n 2.4885\n</code></pre>\n<p>I don't understand if my data are not fitting for a sinusoidal function or just the code is wrong for the sinusoidal fit.</p>\n<p>For acknowledge this is my data set:</p>\n<pre><code>-200 183966\n-192 189734\n-184 195724\n-176 201663\n-168 207557\n-160 213278\n-152 219000\n-144 224677\n-136 229500\n-128 236024\n-120 241968\n-112 247787\n-104 252963\n-96 257491\n-88 261967\n-80 267373\n-72 273494\n-64 278599\n-56 281476\n-48 282610\n-40 283097\n-32 283839\n-24 284971\n-16 286169\n-8 287164\n0 287968\n8 288561\n16 288626\n24 288107\n32 286967\n40 285132\n48 282828\n56 279847\n64 276296\n72 272299\n80 268080\n88 263564\n96 258926\n104 254052\n112 248894\n120 243694\n128 238177\n136 232665\n144 227143\n152 221959\n160 216874\n168 211678\n176 206540\n184 201537\n192 196748\n200 192091\n</code></pre>\n<p>I'm sorry but I'm new to Matlab.\nThank you in advance</p>\n"^^ . . "<p>If you weren't creating a <em>grouped</em> barchart you could make these as <em>stacked</em> bars instead, with the top part of the stack equal to the difference between the two.</p>\n<p>Since you are using a grouped chart, a simple approach would be to plot the taller bars first (with the whole bar red), then <code>hold on</code> and plot the shorter bars.</p>\n<p>You can set the <code>HandleVisibility</code> to <code>off</code> for the red bars so that they don't appear in the legend.</p>\n<p>It would look something like this from your example:</p>\n<pre><code>f = figure('Position', [100, 100, 800, 600]);\n\n% Set &quot;HandleVisibility&quot; to off so these bars don't appear in legend\nb2 = bar(data_with_reflection', 'grouped','HandleVisibility','off');\nfor k = 1:length(b2)\n b2(k).FaceColor = 'flat';\n b2(k).CData = repmat([1,0,0], size(b2(k).CData, 1), 1); % [1,0,0] for red bars\nend\n\n% Plot for No Reflection\nhold on; % To plot 2nd set of bars on top\n\nb1 = bar(data_no_reflection', 'grouped');\nfor k = 1:length(b1)\n b1(k).FaceColor = 'flat';\n b1(k).CData = repmat(custom_colors(k, :), size(b1(k).CData, 1), 1);\nend\n\ngrid on;\nxticks(1:length(QAM));\nxticklabels(string(QAM));\ntitle({'Coverage Area With Reflection', 'm-CAP and DCO-OFDM'});\nlegend([&quot;m-CAP \\Phi_{1/2}=10°&quot;, &quot;m-CAP \\Phi_{1/2}=30°&quot;, &quot;m-CAP \\Phi_{1/2}=45°&quot;, &quot;m-CAP \\Phi_{1/2}=60°&quot;, ...\n &quot;DCO-OFDM \\Phi_{1/2}=10°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=30°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=45°&quot;, &quot;DCO-OFDM \\Phi_{1/2}=60°&quot;], ...\n 'Location', 'Best');\n</code></pre>\n<p>Output:</p>\n<p><a href="https://i.sstatic.net/TgiCR5Jj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TgiCR5Jj.png" alt="figure" /></a></p>\n"^^ . "0"^^ . . . . . . . "0"^^ . "0"^^ . . . . "I tried to set the callbacks after the `plot`. It didn't change anything."^^ . . "0"^^ . . "Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking."^^ . . "<p>I am trying to plot the outputs of quadratic discriminant analysis in MATLAB. I have previously asked about Linear analysis (<a href="https://stackoverflow.com/questions/78871567/plotting-output-of-3d-discriminant-analysis-in-matlab">LDA question for reference</a>), however, now I wish to investigate using quadratic discriminant analysis. For LDA I used fimplicit3 to plot the plain however this requires knowing the form of the equation for the function to evaluate. I am struggling to work out what this should be. The code below works for LDA, but when I change to QDA it is clearly incorrect (you will see when you run the code, the plains intersect the data) as it does not include the extra &quot;quadratic coefficents&quot; introduced by the QDA. I have tried a few things, all unsuccessfully, which I have omitted for clarity.</p>\n<p>In summary, what is the equation I need to pass to &quot;fimplicit3&quot; at line 135, 137, 139, to plot a curved plain? Is there a better way of doing this?</p>\n<p>Beneath the code sample I have included the equations for 2d linear and quadratic, in case this helps.</p>\n<pre><code>clear\nclc\nclose all\n\n%----------------------------\nx1 = 1:0.01:3;\nr = -1 + (1+1)*rand(1,201);\nx1 = x1 + r;\n\ny1 = 1:0.01:3;\nr = -1 + (1+1)*rand(1,201);\ny1 = y1 + r;\n\nz1 = 1:0.01:3;\nr = -1 + (1+1)*rand(1,201);\nz1 = z1 + r;\n\nx1 = x1';\ny1 = y1';\nz1 = z1';\nlabel1 = ones(length(y1),1);\n\nTclust1 = [label1,x1,y1,z1];\n%----------------------------\nx2 = 4:0.01:6;\nr = -1 + (1+1)*rand(1,201);\nx2 = x2 + r;\n\ny2 = 10:0.01:12;\nr = -1 + (1+1)*rand(1,201);\ny2 = y2 + r;\n\nz2 = 10:0.01:12;\nr = -1 + (1+1)*rand(1,201);\nz2 = z2 + r;\n\nx2 = x2';\ny2 = y2';\nz2 = z2';\n\nlabel2 = 2.*ones(length(y2),1);\n\nTclust2 = [label2,x2,y2,z2];\n\n%----------------------------\nx3 = 5:0.01:7;\nr = -1 + (1+1)*rand(1,201);\nx3 = x3 + r;\n\ny3 = 13:0.01:15;\nr = -1 + (1+1)*rand(1,201);\ny3 = y3 + r;\n\nz3 = 13:0.01:15;\nr = -1 + (1+1)*rand(1,201);\nz3 = z3 + r;\n\nx3 = x3';\ny3 = y3';\nz3 = z3';\n\nlabel3 = 3.*ones(length(y3),1);\n\nTclust3 = [label3,x3,y3,z3];\n\n%----------------------------\nT = [Tclust1;Tclust2;Tclust3];\n\ndata = T(:,2:4);\nlabels = T(:,1);\n\n%LOOCV\nn = length(labels);\nhpartition = cvpartition(n,'leaveout');\n\n% figure()\noutput = zeros(n,3);\n\nfor qq = 1:n\n %training data\nidx_Train = training(hpartition,qq);\ndata_Train = data(idx_Train,1:3);\nlabels_Train = labels(idx_Train);\n\n %test data\nidx_Test = test(hpartition,qq);\ndata_Test = data(idx_Test,1:3);\nlabels_Test = labels(idx_Test);\n\n%train the model on the training data\nMdlquad3D = fitcdiscr(data_Train,labels_Train,'Discrimtype','quadratic');\n\n%apply to the testing data\npred_lbl = predict(Mdlquad3D,data_Test);\n\n(qq/n)*100\nend\n\niscorrect=output(:,1)==output(:,2);\naccuracy_full = (sum(iscorrect)/length(iscorrect))*100;\n\n%plot data with boundaries -----------------------------------------------\ndata = T(:,2:4);\nlabels = T(:,1);\nxmin = min(T(:,2));\nxmax = max(T(:,2));\nymin = min(T(:,3));\nymax = max(T(:,3));\nzmin = min(T(:,4));\nzmax = max(T(:,4));\n\n%group 1 and group 2\nK12 = Mdlquad3D.Coeffs(1,2).Const;\nL12 = Mdlquad3D.Coeffs(1,2).Linear;\nQ12 = Mdlquad3D.Coeffs(1,2).Quadratic;\n\n%group 2 and group 3\nK23 = Mdlquad3D.Coeffs(2,3).Const;\nL23 = Mdlquad3D.Coeffs(2,3).Linear;\nQ23 = Mdlquad3D.Coeffs(2,3).Quadratic;\n\n%group 1 and group 3\nK13 = Mdlquad3D.Coeffs(1,3).Const;\nL13 = Mdlquad3D.Coeffs(1,3).Linear;\nQ13 = Mdlquad3D.Coeffs(1,3).Quadratic;\n\nfigure()\nscatter3(x1,y1,z1,'g')\nhold on\nscatter3(x2,y2,z2,'b')\nscatter3(x3,y3,z3,'r')\n\n%THESE ARE CORRECT FOR LDA - HOW TO INCLUDE Qxx? Is there a better way\n%than fimplicit3?\nf12 = @(x1,x2,x3) K12 + L12(1)*x1 + L12(2)*x2 + L12(3)*x3;\nh2 = fimplicit3(f12,[xmin xmax ymin ymax zmin zmax]);\nf23 = @(x1,x2,x3) K23 + L23(1)*x1 + L23(2)*x2 + L23(3)*x3;\nh3 = fimplicit3(f23,[xmin xmax ymin ymax zmin zmax]);\nf13 = @(x1,x2,x3) K13 + L13(1)*x1 + L13(2)*x2 + L13(3)*x3;\nh4 = fimplicit3(f13,[xmin xmax ymin ymax zmin zmax]);\n\ntitle('Full data set')\nxlabel('x')\nylabel('y')\nzlabel('z')\nlegend('Data 1','Data 2','Data 3','Boundary 1 -&gt; 2','Boundary 2 -&gt; 3','Boundary 1 -&gt; 3','location','eastoutside') \n% \n</code></pre>\n<p>For reference:</p>\n<p>2D linear:</p>\n<pre><code>K = MdlLinear.Coeffs(1,2).Const;\nL = MdlLinear.Coeffs(1,2).Linear;\nf12 = @(x1,x2) K + L(1)*x1 + L(2)*x2;\nh2 = fimplicit(f12,[xmin xmax ymin ymax]);\n</code></pre>\n<p>2D Quadratic:</p>\n<pre><code>K = MdlQuad.Coeffs(1,2).Const;\nL = MdlQuad.Coeffs(1,2).Linear;\nQ = MdlQuad.Coeffs(1,2).Quadratic;\nf12 = @(x1,x2) K + L(1)*x1 + L(2)*x2 + Q(1,1)*x1.^2 + (Q(1,2)+Q(2,1))*x1.*x2 + Q(2,2)*x2.^2;\nh2 = fimplicit(f12,[xmin xmax ymin ymax]);\n</code></pre>\n"^^ . "1"^^ . . . . "0"^^ . . . "@Cris happy for OP to clarify further, but I interpreted they're using [this `readValue` function](https://www.mathworks.com/help/icomm/ug/opc.ua.client.readvalue.html) where the 2nd input `nodeList` is an array of [`OPC UA Node` objects](https://uk.mathworks.com/help/icomm/ug/opc-ua-components.html#buzt5x8-2). In my answer I made a struct of such node objects, and then output them as a concatenated array which would be suitable for `readValue`, without having to list them individually as in OP's last line."^^ . . "docker"^^ . . . "scilab"^^ . . "0"^^ . . . "Thanks a lot for the answer! Just one question, I know that `inpolygon` can also return the indices of the points that lays on the boundary of the polygon. Is there a way to use this in order to represent the function f both on the intern of the polygon and on its boundary?"^^ . "<p>I am trying to add vertically the lists of a database like DB (see below) contained in a cell.</p>\n<pre><code>DB={ {[11 12]} {[13 14]} {[15 16]} {[17 18]} {[19 20]};\n\n {[21 22]} {[23 24]} {[25 26]} {[27 28]} {[29 30]};\n\n {[31 32]} {[33 34]} {[35 36]} {[37 38]} {[39 40]}}\n</code></pre>\n<p>I would like to get:</p>\n<pre><code> [33 36] [69 72] [75 78] [81 44] [ 87 90 ]\n</code></pre>\n<p>I tried with a 'for' loop (see below) ... but taking too much time.</p>\n<p>How could I do this with the minimum of 'for' loops or even better, without any loop?</p>\n<p>Thank you very much for your attention.</p>\n<pre><code>sum=[ ]\nfor j=1:5\n sumi=0\n for i=1:3\n sumi=sumi+ c2{i,j}{1}\n end\n sum=[sum sumi]\nend\n</code></pre>\n"^^ . . "1"^^ . . . . "elevated-privileges"^^ . . . "2"^^ . "0"^^ . "How to dynamically update a single plot for multiple iterations in Python (equivalent to MATLAB drawnow)?"^^ . "0"^^ . . . "1"^^ . . "<p>If you already have the green path and just want to divide it in segments, I'd transform the coordinates of the green paths into a logical matrix. Then you can easily find the borders of the segment and display it as you want.</p>\n<pre><code>matrixSize = 600;\n\n%Your green path 2 column vector\nxPositions = greenPath(:,1);\nyPositions = greenPath(:,2);\n\n%Transform to logical matrix\ngreenPathMat = false(matrixSize);\nidx = sub2ind([matrixSize, matrixSize], yPositions, xPositions);\ngreenPathMat(idx) = true;\n\n%Get border in x and y direction\nxBorders = diff(m,1,2);\nyBorders = diff(m,1,1);\n\n%Get Start and End\nxStart = find(any(xBorders==1)) + 1;\nxEnd = find(any(xBorders==-1));\n\nyStart = find(any(yBorders==1,2)) + 1;\nyEnd = find(any(yBorders==-1,2));\n\n%Check if there are any values at matrix borders to add them to start/end\nif any(greenPathMat(:,1)); xStart = [1 xStart]; end\n\nif any(greenPathMat(:,end)); xEnd = [xEnd, matrixSize]; end\n\nif any(greenPathMat(1,:)); yStart = [1; yStart]; end\n\nif any(greenPathMat(end,:)); yEnd = [yEnd; matrixSize]; end\n\n%Calc number of segments\nnbSegments = length(xStart) * 2;\n\nif length(xStart) == length(xEnd)\n nbSegments = nbSegments - 1;\nend\n\n%Display path in black and white\nimagesc(greenPathMat)\nset(gca,&quot;YDir&quot;,&quot;normal&quot;)\nhold on\ncolormap gray\n\nfor ii = 1:floor(nbSegments/2)\n %Vertical segments\n plot(polyshape([xStart(ii) xStart(ii) xEnd(ii) xEnd(ii)],...\n [yStart(ii) yEnd(ii) yEnd(ii) yStart(ii)]));\n\n %Horizontal segments\n plot(polyshape([xStart(ii) xStart(ii) xEnd(ii+1) xEnd(ii+1)],...\n [yStart(ii+1) yEnd(ii) yEnd(ii) yStart(ii+1)]));\nend\n\n%If last segment is vertical\nif length(xStart) == length(xEnd)\n plot(polyshape([xStart(ii+1) xStart(ii+1) xEnd(ii+1) xEnd(ii+1)],...\n [yStart(ii+1) yEnd(ii+1) yEnd(ii+1) yStart(ii+1)]));\nend\n</code></pre>\n<p>If you plot them one by one it looks like this.\n<a href="https://i.sstatic.net/p94dBDfg.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/p94dBDfg.gif" alt="Segment animation" /></a>\nIs this what you want?</p>\n"^^ . . . . . . . . . "0"^^ . . . . "I appreciate then answer for clarification. I knew that link goes to github it is just I was confused because the function name was same in both places. So just wanted to post and get clarification from the communiy. Thanks again you have saved me from writing my own funtion ;)"^^ . . . . . . . "As this is rather a signal processing question than a programming question I recommend to ask it at [DSP.se](https://dsp.stackexchange.com/questions)"^^ . . . "1"^^ . . . . "2"^^ . "5"^^ . "heartrate"^^ . "Could you [edit] your question to include a [mcve] in each language, such that we can copy/paste your code and reproduce the result you're seeing?"^^ . . . . . . . . "<p>I am using MATLAB Actxserver to generate an Excel spreadsheet. A portion of this code is used to generate a formula for determining if any values in a list are different.\nBelow is an example MATLAB code</p>\n<pre><code>c = cell(1,4);\nc{4} = &quot;=IF(AND(EXACT(A1:C1,A1)),0,1)&quot;; \nwritecell(c,'test2.xlsx','UseExcel',true);\n</code></pre>\n<p>However, when I open the Excel file, it replaces the function with</p>\n<pre><code>=IF(AND(EXACT(@A1:C1,A1)),0,1)\n</code></pre>\n<p>The addition of the &quot;@&quot; symbol breaks the function and causes the cell to display &quot;#VALUE!&quot;. If I remove the &quot;@&quot; symbol in Excel, the function works as expected.</p>\n<p>How do I stop Excel from automatically adding the &quot;implicit intersection&quot; symbol?</p>\n<p>I tried using a find and replace function within MATLAB as shown below, and it does not solve the issue. The &quot;@&quot; re-appears.</p>\n<pre><code>Excel = actxserver('excel.application');\nWB = Excel.Workbooks.Open(oufFile,0,false);\nWS = WB.Worksheets.Item(1);\nWS.Range('A1:Z100').Replace(&quot;@&quot;,&quot;&quot;)\nWB.Save();\nWB.Close();\nExcel.Quit();\n</code></pre>\n"^^ . "I think it's related to the in-memory module not seeing the updates. I get this often when I put a python module running under WSGI.. Need to restart the whole webserver."^^ . . . "latex"^^ . "3"^^ . . . "2"^^ . "<p>I would like to update the content of an executable inside a generated executable MatLab file. The file is generated with MatLab/Simulink compiler.</p>\n<p>Why would I want to do this? Because I need to sign the content of all executable that run on my company pc.</p>\n<p>I know I can open the generated executable as a zip file. Inside I can update or add any file.</p>\n<p>I have found that there is a <code>sig1.xml</code> file that contains the sha512 encoded with base64. So I have updated the sha512 signature of the modified file. But I have an error when opening the executable: <em>CTF archive is invalid</em></p>\n<p>Is there a global signature to update? Or anything else?</p>\n<p>Any advice is welcome!</p>\n"^^ . "1"^^ . "<p>One slightly faster approach is to reduce to a single loop, and pre-allocate the output:</p>\n<pre><code>n = 2;\ns = NaN( 1, n*size(DB,2) );\nfor ii = 1:size(DB,2)\n col = vertcat(DB{:,ii});\n s(n*(ii-1)+1:n*ii) = sum( vertcat(col{:}) );\nend\n</code></pre>\n<p>Note that <code>n</code> here is the number of elements within each cell, which in your example was <code>2</code>.</p>\n"^^ . . . "2"^^ . "Hi Wolfie, \nThank you for your comment. Your example is exactly what I’m trying to do! However, when I changed the order of yfill (min(zaxis) * ones(size(b))and b), it gave me the same result.\n\nAt first, I wondered if MATLAB might be confused because min(zaxis) is a constant value, but based on your example, I guess that’s not the issue.\nCould it be that the problem arises because b is not defined as an equation?"^^ . "0"^^ . . . . . "machine-learning"^^ . . . "0"^^ . . "0"^^ . . "You posted two images that look identical to me. I don’t see any stripes."^^ . . . "0"^^ . . . . . "Finally i did a restart of python as well as matlab and it works now. What I also tested is, that when i change something in the python code and want to run it with matlab, I always have to restart matlab such that the updated code gets properly executed, otherwise the "old" code gets executed, this was totally unexpected for me and somehow strange - any reason for this?"^^ . . . . "0"^^ . "0"^^ . "1"^^ . . . . . "0"^^ . . . . . "3"^^ . "How to include a LaTeX expression in a web page built with the Matlab Publish?"^^ . "<p>The goal invoke .bat files with administrative privilege from MATLAB. The Windows user account is a member of the administrators group, however, invoking the date command to change the system date / time returns insufficient privilege and seems to require an &quot;administrative&quot; terminal.</p>\n<p>I am starting with the Andrew Janke <a href="https://stackoverflow.com/a/8932157/4953146">solution</a> and would like to run a .bat file that requires administrative privilege (date command is in the .bat file). I have successfully run simple batch files with commands known not to require privileges.</p>\n<p>The crux of the said Janke solution is:</p>\n<pre><code>startInfo = `System.Diagnostics.ProcessStartInfo`('cmd.exe', sprintf('/c &quot;%s&quot;', batFile));\n</code></pre>\n<p>Is there an argument that be added to modify cmd.exe <em>or</em> elsewhere in the parentheses owned by <code>System.Diagnostics.ProcessStartInfo</code>.</p>\n<p>What is the syntax to elevate the privilege of call to <code>cmd.exe</code>?</p>\n<p>My Google search failed to turn up a simple solution. What I did find seemed to be on the right track but I would prefer a simple argument for the said function: <a href="https://stackoverflow.com/questions/2532769/how-to-start-a-process-as-administrator-mode-in-c-sharp">How to start a Process as administrator mode in C#</a></p>\n"^^ . . . "1"^^ . . "0"^^ . "0"^^ . . . "@RPM For me, this is what I thought about presenting them, but if there is another creative idea to show them, I'll be happy to know."^^ . "0"^^ . . . . . "<p>In Simulink, I defined a Discrete State Space model. However it only has a an input port for u and another for y, but I need to track the state x. How can I do it without building a state observer (which in this case should not be needed since the input is generated from Simulink itself with step blocks)? Note that I cannot modify C to be eye(n) and D to be zeros(n,m), because the discrete system I'm working with comes from the minimal representation of an identified transfer function, so I cannot just modify the matrices because that would modify the underlying process too.</p>\n"^^ . "0"^^ . "0"^^ . "0"^^ . . "<p><em>Note: I tried this with <a href="https://octave.org/" rel="nofollow noreferrer">Octave</a>, since I don't have a MATLAB license.</em></p>\n<p>As already hinted at in the comments, your communication between your MATLAB script and your Python script is missing two essential aspects:</p>\n<ul>\n<li>The handling of the inputs to the Python script within the Python script.</li>\n<li>The handling of the results from the Python script within the MATLAB script.</li>\n</ul>\n<h2>Handling the inputs to the Python script</h2>\n<p>This is the easier part:</p>\n<ul>\n<li>Calling <code>system('python script.py argA argB')</code> from MATLAB results in calling the Python script <code>script.py</code> with command line arguments <code>argA</code> and <code>argB</code>.</li>\n<li>From within the called Python script <code>script.py</code>, the command line arguments are available via <code>sys.argv</code>, which is a list of strings.</li>\n</ul>\n<p>Let's assume you have a Python script <code>script.py</code> with the following contents:</p>\n<pre class="lang-py prettyprint-override"><code>### Contents of 'script.py' ###\nimport sys\nprint(sys.argv)\n</code></pre>\n<p>Call this script from the command line via the following call:</p>\n<pre class="lang-none prettyprint-override"><code>$ python script.py argA argB\n</code></pre>\n<p>Then your output will look as follows:</p>\n<pre class="lang-none prettyprint-override"><code>['script.py', 'argA', 'argB']\n</code></pre>\n<p>As you can see, all command line arguments are available as strings, prepended by the name (or path) of the called script itself. You can now actually make use of them from within your script; for example, convert them to numbers for calculations or, as in your case, use them as a name for a file to be loaded.</p>\n<h2>Handling the outputs of the Python script</h2>\n<p>This is the more tricky part, and I am not sure if mine is the best solution:</p>\n<p>Once you have done all the data processing in your Python script, you somehow need to get the results back to MATLAB. A very straightforward approach would be printing the results within the Python script and then capturing the outputs as part of the return value of the <code>system()</code> call in your MATLAB script.</p>\n<p>Let's assume you still have the Python script <code>script.py</code>, with the same contents as above. Additionally now, let's assume we have a MATLAB script <code>script.m</code> with the following contents:</p>\n<pre class="lang-matlab prettyprint-override"><code>%%% Contents of 'script.m' %%%\n[status, output] = system('python script.py argA argB');\nsprintf('From python: %s', output)\n</code></pre>\n<p>Call this script from the command line via the following call (again, I am using Octave here):</p>\n<pre class="lang-none prettyprint-override"><code>$ octave script.m\n</code></pre>\n<p>Then your output will look as follows:</p>\n<pre class="lang-none prettyprint-override"><code>ans = From python: ['script.py', 'argA', 'argB']\n</code></pre>\n<p>As you can see, we got the same output, but this time from the MATLAB script (and only from the MATLAB script). The MATLAB script captured the Python output in the <code>output</code> variable, then processed it (by prepending <code>'From python: '</code>), and printed it again.</p>\n<h2>Putting it all together into a (somewhat) more useful example</h2>\n<p>We can use the same approach to pass not only strings but actual data. For this case we might want to write raw bytes to the output from within our Python script, then parse them from within our MATLAB script and convert them to a corresponding MATLAB object.</p>\n<p>The following example …</p>\n<ul>\n<li>(in MATLAB) sends a number <code>n</code> to Python as a command line argument;</li>\n<li>(in Python) creates an <code>n×n</code> square matrix containing the values <code>0,1,…,n²-2,n²-1</code> as a 2D Numpy array, then prints the raw bytes of the corresponding <code>float64</code> values;</li>\n<li>(in MATLAB) captures the raw bytes and converts them to the corresponding 2D MATLAB array of <code>double</code> values.</li>\n</ul>\n<p>Python script <code>script.py</code>:</p>\n<pre class="lang-py prettyprint-override"><code>### Contents of 'script.py' ###\nimport sys\nimport numpy as np\n\n# Convert 1st argument to integer, then create square matrix of doubles with it\nnum = int(sys.argv[1])\ndata = np.arange(num*num, dtype=np.float64).reshape(num, num)\n# Write resulting bytes to stdout\nsys.stdout.buffer.write(data.tobytes())\n</code></pre>\n<p>MATLAB script <code>script.m</code>:</p>\n<pre class="lang-matlab prettyprint-override"><code>%%% Contents of 'script.m' %%%\nrows_cols = 3;\n[status, res] = system(sprintf('python script.py %d', rows_cols));\nnumpy_data = reshape(typecast(uint8(res), 'double'), [rows_cols, rows_cols])'\n</code></pre>\n<p>Command line call of Octave and corresponding output:</p>\n<pre class="lang-none prettyprint-override"><code>$ octave script.m\nnumpy_data =\n\n 0 1 2\n 3 4 5\n 6 7 8\n\n</code></pre>\n<p>As you can see, the 2D array was successfully reinstantiated as the MATLAB array <code>numpy_data</code>.</p>\n<p>In reality, this might be trickier, of course: For example, if the Python script produces more outputs other than only the raw data that we are actually interested in, we need to filter out the parts that we are interested in (on the MATLAB side) or suppress all unrelated outputs (on the Python side). Also, getting the numbers of bytes, shapes, and orders of dimensions correct might not always be as straightforward as in the given example (note, for example, that here we needed to transpose the final MATLAB result).</p>\n"^^ . . . . "1"^^ . . . "0"^^ . . "@Davide trying to understand why you might want that - are you asking because you want to plot an outline to the surface? Most likely very few of the mesh points used in this approach actually lie _on_ the boundary, but depending what you're trying to achieve there is likely another approach..."^^ . "2"^^ . . "Same as Wolfie! I had a vague idea but couldn’t turn it into a concrete solution. I really like this approach.\n\nBased on my experience, numerical matrices generally enhance MATLAB performance compared to using cells."^^ . "<p>i encountered the problem that when calling a python function within the matlab environment, the return value from python is not recognized in matlab - i always get a py.NoneType as an output.</p>\n<p>Here my code, it is a code to send E-mails. I can see the print commands as an output in matlab but cannot capture the return values properly (always a py.NoneType in Matlab). When calling the function directly from python everything works fine.</p>\n<p>What could the problem be ?</p>\n<pre><code>import smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nimport os\n\ndef send_email(gmail_user, gmail_password, to_email, subject, body, attachment_path):\n &quot;&quot;&quot;\n Send an email with an attachment using Gmail's SMTP server.\n\n Parameters:\n gmail_user (str): Your Gmail email address\n gmail_password (str): Your Gmail app password\n to_email (str): Recipient's email address\n subject (str): Subject of the email\n body (str): Body text of the email\n attachment_path (str): Full path to the attachment file\n &quot;&quot;&quot;\n try:\n # Create the email\n email = MIMEMultipart()\n email['From'] = gmail_user\n email['To'] = to_email\n email['Subject'] = subject\n\n # Add the email body\n email.attach(MIMEText(body, 'plain'))\n\n # Normalize the file path\n attachment_path = attachment_path.encode('utf-8').decode('utf-8')\n attachment_path = os.path.normpath(attachment_path)\n # attachment_path = attachment_path.replace(&quot;\\\\&quot;, &quot;\\\\\\\\&quot;)\n print(f&quot;Processed attachment path: {attachment_path}&quot;)\n\n # Check if the attachment file exists\n if not os.path.exists(attachment_path):\n print(f&quot;Error: The file {attachment_path} does not exist.&quot;)\n return 'Name in Email not correct!';\n \n\n # Open the file in binary mode and encode it\n with open(attachment_path, 'rb') as attachment_file:\n attachment = MIMEBase('application', 'octet-stream') # Generic MIME type, could be more specific\n attachment.set_payload(attachment_file.read())\n encoders.encode_base64(attachment)\n\n # Extract filename from the path\n filename = os.path.basename(attachment_path)\n print(f&quot;Attachment found: {filename}&quot;)\n\n # Add header for the attachment\n attachment.add_header('Content-Disposition', 'attachment', filename=filename)\n\n # Attach the file to the email\n email.attach(attachment)\n print(f&quot;Attachment '{filename}' added successfully.&quot;)\n return 'yes'\n\n # Send the email using Gmail's SMTP server\n with smtplib.SMTP('smtp.gmail.com', 587) as server:\n server.starttls() # Secure the connection\n server.login(gmail_user, gmail_password)\n server.sendmail(gmail_user, to_email, email.as_string())\n print(&quot;Email sent successfully!&quot;)\n \n return 'Email sent!'\n\n except Exception as e:\n print(f&quot;Failed to send email: {e}&quot;)\n return 'Email failed fatal!'\n \n return &quot;Unknown error occurred.&quot;\n\n\n</code></pre>\n<p>Thanks in advance</p>\n<p>I tried a &quot;mini example&quot; with a simple python function (just adding two numbers) and it worked, so I have no idea why the more advanced code does not work.</p>\n<p>No errors are showing up in Matlab and also no details from the python code.</p>\n<p>My expectation was that when calling the function from Matlab like <code>output=py.send_email.send_email(Arguments)</code><br>\nThe variable &quot;output&quot; holds the string 'Email sent!', but instead is always py.NoneType.</p>\n<p>I built in some print statement just to check if Matlab prints it properly, and it does ! The email is being sent as it should. I just want an output variable for some extra coding in Matlab. I also get no return when i use the wrong path where I should get 'Name in Email not correct!', and this is just at the beginning.</p>\n"^^ . "0"^^ . "data-analysis"^^ . "2"^^ . "1"^^ . "0"^^ . "3"^^ . . . . . "0"^^ . . "0"^^ . "<p>I am now creating a MATLAB script to read the release versions in which a sldd object is created in Simulink/MATLAB.</p>\n<p>For example, An SLX file <strong>activeSuspension.slx</strong>'s matlab version it has been saved in can be retrieved using <strong>Simulink.MDLInfo</strong> object and it's property '<strong>ReleaseName</strong>'.</p>\n<pre><code>mdlInfo= Simulink.MDLInfo('activeSuspension');\nmatlabVersion=mdlInfo.ReleaseName;\n</code></pre>\n<p>From documentation <a href="https://in.mathworks.com/help/simulink/slref/simulink.mdlinfo.html" rel="nofollow noreferrer">https://in.mathworks.com/help/simulink/slref/simulink.mdlinfo.html</a> I am aware that MDLInfo is only limited to .slx,.slxp and .mdl files.</p>\n<p>Now coming to my query, I would like to know if there is any direct API command like MDLInfo or a resuable script available to get the matlab version created for a .sldd file.</p>\n<p><a href="https://i.sstatic.net/TMKeLjUJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TMKeLjUJ.png" alt="Metadata visible in GUI of Matlab for .sldd file" /></a></p>\n<p>Since the metadata is visible in MATLAB UI for a .sldd file I believe there is a solid possibility to have an API command from which the &quot;Saved in Simulink &quot; version can be found, but I am unlucky so far to find one from documentation. Thanks in advance</p>\n"^^ . . . . . . . . . . . . "Avoid "implicit intersection" symbol addition to Excel formulas when using MATLAB Actxserver"^^ . "2"^^ . "0"^^ . . "0"^^ . . "2"^^ . "2"^^ . . . "1"^^ . "0"^^ . . . "<p>Could this help you?</p>\n<pre><code>m = reshape(M,N,N,N*N);\n</code></pre>\n"^^ . . . . . "polygon"^^ . . . . "0"^^ . "How to use C caller block in Simulink"^^ . "Adding word boundaries fixes it: `(\\b[a-zA-Z_]\\w*\\b)(?!\\s*\\()`"^^ . . . . "2"^^ . . "2"^^ . "1"^^ . "audio"^^ . . "0"^^ . . . "batch-file"^^ . "<p>I am trying to automate the Doxygen documentation build for a MATLAB library using BitBucket pipelines. Doxygen doesn't support MATLAB natively, so I am using the <code>m2cpp.pl</code> filter developed by <a href="https://uk.mathworks.com/matlabcentral/fileexchange/25925-using-doxygen-with-matlab" rel="nofollow noreferrer">Fabrice</a>. My Doxyfile is default apart from the following settings. <code>FILTER_PATTERNS</code> tells Doxygen to use the filter and <code>PERL_PATH</code> tells Doxygen where to find the installation of Perl needed to run the filter.</p>\n<pre><code>EXTENSION_MAPPING = .m=C++\nFILTER_PATTERNS = *.m=m2cpp.pl\nPERL_PATH = C:\\Strawberry\\perl\\bin\n</code></pre>\n<p>After some daft problems with relative filepaths etc, I was able to run this on my Windows laptop with the latest version of Doxygen and it produces the expected HTML files documenting my MATLAB library.</p>\n<p>Then I tried to repeat the same inside of a Docker Container, so that I can automate this process with BitBucket Pipelines. I have tried two Doxygen images: <a href="https://hub.docker.com/r/corentinaltepe/doxygen" rel="nofollow noreferrer">corentinaltepe/doxygen</a> and <a href="https://hub.docker.com/r/hrektts/doxygen" rel="nofollow noreferrer">hrektts/doxygen</a>. I changed the filepaths accordingly and Doxygen runs 'fine' but produces blank documentation.</p>\n<pre><code>EXTENSION_MAPPING = .m=C++\nFILTER_PATTERNS = *.m=/usr/local/bin/m2cpp.pl\nPERL_PATH = /usr/bin/perl\n</code></pre>\n<p>The Doxygen readout always includes <code>sh: 1 /usr/local/bin/m2cpp.pl: not found</code>. I get the same message when I run the container locally or through a pipeline. Moreover, I have even run the container in interactive mode and used the shell to check that the file is present. On one occaision, I had these consecutive lines in the terminal...</p>\n<pre><code>root@6a1b63b93f6d:/# /usr/local/bin/doxy/m2cpp.pl\nbash: /usr/local/bin/doxy/m2cpp.pl: /usr/bin/perl.exe^M: bad interpreter: No such file or directory\nroot@6a1b63b93f6d:/# ls -l /usr/local/bin/doxy/m2cpp.pl\n-rwxrwxrwx 1 1001 1001 6892 Jan 24 15:48 /usr/local/bin/doxy/m2cpp.pl\n</code></pre>\n<p>... where Line 2 says <code>No such file</code> and then Line 4 confirms I have <code>rwx</code> permission for the very same file. I have tried several different options for putting the file in different places, accessing it via different paths etc, and its always the case that the Doxygen readout says <code>not found</code>.</p>\n"^^ . . "1"^^ . . . "<h1>Reasons</h1>\n<p>There are two places you need to change in your <code>R</code> code, since their definitions are absolutely different from the <code>Matlab</code> functions</p>\n<ul>\n<li><code>diag</code>: In <code>R</code>, the argument <code>k</code> in <code>diag(v,k)</code> refers to the number of rows of the diagonal matrix, instead of the expected &quot;the position of diagonal&quot; (as done by <code>Matlab</code>)</li>\n<li><code>trace</code>: In <code>R</code>, the function <code>trace</code> is a call to interactively keep track of debugging, rather than computing the trace of a matrix (as done by <code>Matlab</code>)</li>\n</ul>\n<hr />\n<h1>Fixups</h1>\n<ul>\n<li>regarding <code>diag</code>, you should define a customized <code>diag</code> function to mimic the version in <code>Matlab</code>, e.g.,</li>\n</ul>\n<pre><code>fdiag &lt;- function(v, k) {\n n &lt;- length(v) + abs(k)\n mat &lt;- matrix(0, n, n)\n replace(mat, col(mat) - row(mat) == k, v)\n}\n</code></pre>\n<ul>\n<li>Regarding <code>trace</code>, you should replace it by <code>matrix_trace</code>, which is from <code>CVXR</code> package itself and is dedicated to compute the trace of a function, as desired.</li>\n</ul>\n<hr />\n<h1><code>R</code> Code with Above Fixups</h1>\n<pre><code>fdiag &lt;- function(v, k) {\n n &lt;- length(v) + abs(k)\n mat &lt;- matrix(0, n, n)\n replace(mat, col(mat) - row(mat) == k, v)\n}\n\n\nlibrary(CVXR)\ncompute_Q &lt;- function(n, p, Y) {\n R &lt;- Y\n s &lt;- n * (p + 1)\n Q &lt;- Variable(s, s, symmetric = TRUE)\n\n # Objective: Maximize trace of the top-left block of Q\n objective &lt;- Maximize(sum(diag(Q[1:n, 1:n])))\n\n # Constraints: Q is positive semidefinite\n constraints &lt;- list(Q %&gt;&gt;% 0)\n\n # Add trace constraints for each block\n for (k in 0:p) {\n ind_diag &lt;- fdiag(rep(1, p + 1 - k), k)\n for (i in 1:n) {\n for (j in 1:n) {\n ind_bl &lt;- matrix(0, n, n)\n ind_bl[i, j] &lt;- 1\n constraints &lt;- c(\n constraints,\n matrix_trace(Q %*% kronecker(ind_diag, ind_bl)) == R[[k + 1]][i, j]\n )\n }\n }\n }\n\n # Solve the problem\n problem &lt;- Problem(objective, constraints)\n result &lt;- solve(problem, solver = &quot;SCS&quot;)\n\n # Return the computed Q matrix\n return(result$getValue(Q))\n}\n</code></pre>\n<p>gives</p>\n<pre><code>&gt; (Q &lt;- compute_Q(n, p, Y))\n [,1] [,2] [,3] [,4] [,5] [,6] [,7]\n [1,] 2.1225066 0.1298917 0.1313423 0.1330286 0.1229291 0.18490392 0.20608872\n [2,] 0.1298917 2.1167175 0.1294767 0.1147492 0.1192947 0.19428491 0.20741411\n [3,] 0.1313423 0.1294767 2.1451438 0.1356292 0.1244219 0.18659984 0.19448594\n [4,] 0.1330286 0.1147492 0.1356292 2.1293226 0.1327116 0.22317303 0.19743112\n [5,] 0.1229291 0.1192947 0.1244219 0.1327116 2.1144291 0.20766400 0.21232930\n [6,] 0.1849039 0.1942849 0.1865998 0.2231730 0.2076640 0.07586326 0.07674252\n [7,] 0.2060887 0.2074141 0.1944859 0.1974311 0.2123293 0.07674252 0.07869718\n [8,] 0.1936580 0.1904798 0.1887651 0.2047515 0.1948370 0.07350616 0.07488188\n [9,] 0.2057208 0.1798707 0.1946745 0.1884569 0.2092434 0.07366851 0.07536945\n[10,] 0.2185528 0.2280651 0.1985803 0.1967429 0.1989896 0.07826099 0.08026212\n [,8] [,9] [,10]\n [1,] 0.19365803 0.20572083 0.21855281\n [2,] 0.19047982 0.17987071 0.22806510\n [3,] 0.18876506 0.19467445 0.19858034\n [4,] 0.20475154 0.18845692 0.19674291\n [5,] 0.19483701 0.20924341 0.19898959\n [6,] 0.07350616 0.07366851 0.07826099\n [7,] 0.07488188 0.07536945 0.08026212\n [8,] 0.07183425 0.07193995 0.07652456\n [9,] 0.07193995 0.07283130 0.07689358\n[10,] 0.07652456 0.07689358 0.08260348\n</code></pre>\n"^^ . . . . "<p>It can be fixed by using</p>\n<pre><code>system('python [.py filename]')\n</code></pre>\n<p>Thanks to @Cris Luengo for the solution</p>\n"^^ . . . "1"^^ . . "1"^^ . . . . . "<p>Try the following:</p>\n<ol>\n<li><p>Ensure MATLAB R2022b runs and <code>extern/engines/python/setup.py</code> exists.</p>\n</li>\n<li><p>Install:</p>\n<pre class="lang-bash prettyprint-override"><code>pip install setuptools==58.0.4 wheel\n</code></pre>\n</li>\n<li><p>Install Engine:</p>\n<pre class="lang-bash prettyprint-override"><code>cd &quot;matlabroot/extern/engines/python&quot;\npython -m pip install .\n</code></pre>\n</li>\n</ol>\n"^^ . "2"^^ . "2"^^ . "0"^^ . "mathematical-optimization"^^ . . . . . . . . . "avoid using `sum` as a variable name, you're shadowing the [in-built function](https://www.mathworks.com/help/matlab/ref/double.sum.html) which can cause unexpected errors"^^ . . "0"^^ . "0"^^ . . "legend"^^ . "3"^^ . . "2"^^ . . . "1"^^ . . "0"^^ . "<p>I cannot figure out why my Matlab code for extrapolating susceptibility using the reweighting method returns physically non-sensical graphs, even though the magnetization and energy series appear fine. Here's what the code looks like:</p>\n<pre><code>load(&quot;M_abs.mat&quot;, &quot;M_cb_abs1&quot;); % normalized absolute magnetization\nload(&quot;E.mat&quot;, &quot;E_cb1&quot;); % normalized energy\n\nM = M_cb_abs1;\nE = E_cb1;\n\nglobal L beta_cr n_sample\nL = 20; % lattice size\nbeta_cr = 0.41; % inverse critical temperature estimate\nN_cr = 3*10^5; % MC steps at beta_cr\nn_sample = 0.8 * N_cr; % post-thermalization MC steps\n\nbeta_min = 0.3;\nbeta_max = 0.6;\ndel_beta = 0.01;\nbetas=beta_min:del_beta:beta_max; % temperature range for reweighting\n\nchi = zeros(1, length(betas));\n for i=1:length(betas)\n rw = reweight(M, E, betas(i));\n [chi(i)] = deal(rw{:});\n end\n\nfunction rw = reweight(M, E, beta)\nglobal n_sample beta_cr L\n\ndelta = beta_cr - beta;\nsum1_M = 0; sum1_M2 = 0; sum2 = 0;\n\nfor i = 1:n_sample\n w = exp(delta * E(i));\n sum1_M = sum1_M + M(i) * w;\n sum1_M2 = sum1_M2 + M(i)^2 * w;\n sum2 = sum2 + w;\nend\n\nM_abs_avg = sum1_M / sum2;\nM2_avg = sum1_M2 / sum2;\n\nchi = beta * L^2 * (M2_avg - M_abs_avg^2);\n\nrw = {chi};\nend\n</code></pre>\n<p>The resulting graph is an almost linear, increasing function instead of the expected susceptibility peak at beta_cr.</p>\n"^^ . "0"^^ . . . "1"^^ . . . . . "1"^^ . . "The time shifting property of the Fourier transform states that the magnitude spectrum should not change, however, there should be a linear shift in the phase spectrum."^^ . . . "If you want to build a DLL with MinGW, you need to add `-shared` to the command line arguments of gcc."^^ . "0"^^ . . "Error: Arrays have incompatible sizes for this operation during Grad-Cam for 3D CNN (MatLab)"^^ . "distance"^^ . . . "0"^^ . . . "0"^^ . "0"^^ . "1"^^ . "0"^^ . . "<p>I'm trying to create a DLL from a set of MatLab scripts and a matching wrapper DLL (I need it to adapt functions calls/parameters to be used in LabView).</p>\n<p>Creating the DLL from the MatLab script goes pretty straightforward there are many examples, I got all the files that such compilation is supposed to produce (.dll, .h, .lib, .def etc).</p>\n<p>I followed a template for <em>making</em> the wrapper and the resuling source seems correct but when I try to compile it with this command:</p>\n<pre><code>mbuild -v A0007121_3LIV_W.c A0007121_3LIV.lib LINKFLAGS=&quot;$LINKFLAGS /DLL /DEF:A0007121_3LIV_W.def&quot; LDEXT=&quot;.dll&quot; CMDLINE250=&quot;mt -outputresource:$EXE';'2 -manifest $MANIFEST&quot;\n</code></pre>\n<p>I got this:</p>\n<pre><code>Verbose mode is on.\n... Looking for compiler 'MinGW64 Compiler (C)' ...\n ... Looking for environment variable 'MW_MINGW64_LOC' ...Yes ('C:\\mingw64').\n ... Looking for file 'C:\\mingw64\\bin\\gcc.exe' ...Yes.\n ... Looking for folder 'C:\\mingw64' ...Yes.\n [..]\nBuilding with 'MinGW64 Compiler (C)'.\nC:\\mingw64\\bin\\gcc -c -DMATLAB_DEFAULT_RELEASE=R2017b -DUSE_MEX_CMD -m64 -I&quot;C:\\Program Files\\MATLAB\\R2019b/extern/include&quot; -I&quot;C:\\Program Files\\MATLAB\\R2019b/simulink/include&quot; -I&quot;C:\\Program Files\\MATLAB\\R2019b/extern\\lib\\win64\\mingw64&quot; -I&quot;C:\\Program Files\\MATLAB\\R2019b\\extern\\include\\win64&quot; -fexceptions -fno-omit-frame-pointer -O2 -fwrapv -DNDEBUG &quot;C:\\Users\\m.santucci\\Documents\\MATLAB\\SIRIO\\A0007121_3LIV\\A0007121_3LIV_W.c&quot; -o C:\\Users\\MAB0B~1.SAN\\AppData\\Local\\Temp\\5\\mex_4521000822066357_3928\\A0007121_3LIV_W.obj\nC:\\mingw64\\bin\\gcc -m64 -Wl,--no-undefined,--out-implib,&quot;A0007121_3LIV_W.lib&quot; -s C:\\Users\\MAB0B~1.SAN\\AppData\\Local\\Temp\\5\\mex_4521000822066357_3928\\A0007121_3LIV_W.obj A0007121_3LIV.lib -L&quot;C:\\Program Files\\MATLAB\\R2019b\\extern\\lib\\win64\\mingw64&quot; -lmclmcrrt -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32 -o A0007121_3LIV_W.dll\nError using mbuild (line 166)\nUnable to complete successfully.\nC:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/6.3.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x2e):\nundefined reference to `WinMain'\ncollect2.exe: error: ld returned 1 exit status\n</code></pre>\n<p>I'm using MatLab 2019b, MinGW-W64 6.3.0</p>\n<p>--- SOURCES ---</p>\n<p>Script source.</p>\n<pre class="lang-matlab prettyprint-override"><code>function [SNR_dB, PhaseNoise_mean] = Misura_SNR_con_SBX(FullName, Figure_path)\n ...\nend\n</code></pre>\n<p>Wrapper header.</p>\n<pre class="lang-none prettyprint-override"><code>#ifndef A0007121_3LIV_W\n#define A0007121_3LIV_W\n\nvoid loadA0007121_3LIV(void);\nvoid unloadA0007121_3LIV(void);\n\nint wmlfMisura_SNR_con_SBX(char* FullName, char* FigurePath, double* SNR_dB, double* PhaseNoise_mean);\n\n#endif\n</code></pre>\n<p>Wrapper code.</p>\n<pre class="lang-none prettyprint-override"><code>#include &quot;A0007121_3LIV_W.h&quot;\n#include &quot;A0007121_3LIV.h&quot;\n\n#include &quot;matrix.h&quot;\n\nvoid loadA0007121_3LIV(void)\n{\n A0007121_3LIVInitialize();\n}\n\nvoid unloadA0007121_3LIV(void)\n{\n A0007121_3LIVTerminate();\n}\n\nint wmlfMisura_SNR_con_SBX(char* FullName, char* FigurePath, double* SNR_dB, double* PhaseNoise_mean)\n{\n int result = 1;\n\n mxArray* mFullName = mxCreateString(FullName);\n mxArray* mFigure_path = mxCreateString(FigurePath);\n\n int nargout = 2;\n\n mxArray* mSNR_dB = NULL;\n mxArray* mPhaseNoise_mean = NULL;\n\n //int nargout, mxArray** SNR_dB, mxArray** PhaseNoise_mean, mxArray* FullName, mxArray* Figure_path\n result = mlfMisura_SNR_con_SBX(\n nargout, \n &amp;mSNR_dB, \n &amp;mPhaseNoise_mean, \n mFullName, \n mFigure_path);\n\n //TODO: outputs ?\n\n memcpy(SNR_dB, mxGetPr(mSNR_dB), sizeof(double));\n memcpy(PhaseNoise_mean, mxGetPr(mPhaseNoise_mean), sizeof(double));\n\n mxDestroyArray(mFullName);\n mxDestroyArray(mFigure_path);\n mxDestroyArray(mSNR_dB);\n mxDestroyArray(mPhaseNoise_mean);\n\n return result;\n}\n</code></pre>\n<p>Wrapper .def file.</p>\n<pre><code>LIBRARY A0007121_3LIV_W\nEXPORTS\nloadA0007121_3LIV\nunloadA0007121_3LIV\nwmlfMisura_SNR_con_SBX\n</code></pre>\n<p>I can share more details if needed.</p>\n<p>--- EDIT ---</p>\n<p>I tried to add an empty main to the wrapper C code:</p>\n<pre class="lang-none prettyprint-override"><code>int main(int argc, char* argv[])\n{\n}\n</code></pre>\n<p>Now <code>WinMain</code> reference error has been fixed (!?) but I got this:</p>\n<pre><code>'mt' is not recognized as an internal or external command,\noperable program or batch file.\n</code></pre>\n"^^ . "0"^^ . "Converting MATLAB FFT-based Delay Function to CUDA MEX"^^ . "<p>The <code>rpmfreqmap</code> function in matlab has an input option <code>res</code>for frequency resolution. With the output there is also a frequency resolution option <code>res</code>. If I specify a frequency resolution of 1 Hz:</p>\n<pre><code>[map,freq,rpmOut,time,res]=rpmfreqmap(randn(1,100000),3000,linspace(1,100,100000),1,'OverlapPercent',0);\n</code></pre>\n<p>With this the result will be <code>res=1;</code> as expected. But the frequency vector is <code>freq(1:4)=[0 0.6665 1.3330 1.9996]</code>. I would have expected <code>freq(1:4)=[0 1 2 3]</code>.</p>\n<p>Equally with no overlap I would expect the time vector to be <code>time(1:4)=[0.5 1.5 2.5 3.5]</code>, but it is <code>time(1:4)=[0.7502 2.2505 3.7508 5.2512]</code>. So the relationship between frequency and time steps is <code>delta_time=1/delta_freq</code>, but it doesn't align with the specification in <code>res</code>.</p>\n<p>So, how can I derive the frequency step size of the output vector of <code>rpmfreqmap</code>?</p>\n"^^ . . . "I don't need to know where the CTF file is unpacked I need to know where the executable is run from the user... because this's a NON variable path."^^ . . . "-1"^^ . . . "0"^^ . "1"^^ . . "1"^^ . . . "0"^^ . "@jdweng I corrected in the post. R opens MATLAB, displays the result but does not capture it and bring it to the R environment."^^ . . "0"^^ . . . "hittest"^^ . . "version"^^ . . "r"^^ . "Issue with Shifting Aliasing Signal on Time Axis in MATLAB"^^ . . . . . "<p>There are many things possible using <code>coder.ceval</code> - including calling C++. But also many limitations. Currently working on this as well. You can call arrays, but there are limitations if you have typedefs that define array datatypes.</p>\n<p>For inputs and outputs look into the use of <code>coder.rref</code> and <code>coder.wref</code></p>\n<p>So in your example\n<code>\nfunction [a,b,c,d] = callingCcode (x,y)\n% init output by reference variables\nb = 0;\nc = 0;\nd = 0;\na = coder.ceval('Ccode', coder.rref(x), coder.rref(y), ...\ncoder.wref(b), coder.wref(c), coder.wref(d));\n</code></p>\n"^^ . "Is the pattern of your `L` matrix always periodic as in your example? I.e., could you compute `L = repmat(L_block, [3, 4])` or similar? (Not 100% sure if that is what you mean by "permuted block matrix")"^^ . "0"^^ . "0"^^ . . . "@Reinderien it is a mixed integer linear programming. I provided the code."^^ . "0"^^ . . . "You should have included all of this crucial information in the original question at the outset (and it is better to modify the question now since comments are ephemeral). This is like pulling teeth! If you expect to get meaningful help you **have** to provide all of the relevant information. The driver is what it is but knowing that and the physical hardware may provide a way to make it work with some intermediate piece of software acting as a shim. Unusual imaging hardware often has its peculiar quirks :("^^ . . . . "1"^^ . "@Cal Fireflies' solution is _not computing all of `C`_. It only computes its nonzero entries, as a colum vector. Do you need all of `C`, or only that vector? I assumed you needed to get all of `C` as a sparse matrix because your code does that"^^ . "0"^^ . "4"^^ . "Is there any reason for you to believe the two lines are parallel, other that they seem to be so? Have you generated the points by some algorithm, such that the lines are parallel, or have you just selected the points such the lines are "visually parallel"? If the latter is the case, you can't expect such a high standard for parallelism as `abs(cross_product) < 1e-6` to be achieved; rather, your actual `abs(cross_product)` of `0.0631` seems decent."^^ . "0"^^ . . . "<p>I want to show two lines are parallel. In the following plot you can see that the two lines red and blue are parallel. But when I implemented in code, they are not showing as parallel.</p>\n<p><a href="https://i.sstatic.net/Tp1IXb7J.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Tp1IXb7J.jpg" alt="enter image description here" /></a></p>\n<p>The MATLAB code for that</p>\n<pre><code>%Parallel line segment\nclc; clear all;\n\n\nline_segments = [\n \n 0.9226 5.1428 3.1123 5.2620;\n 1.3742 5.4433 3.3678 5.5230;\n \n];\n\n\n\n% Calculate the direction vectors for each line segment\ndirections = [line_segments(:,3) - line_segments(:,1), line_segments(:,4) - line_segments(:,2)];\n\n% Threshold for parallelism (to account for floating point precision)\nthreshold = 1e-6;\n\n% Find parallel line segments\nparallel_pairs = [];\nfor i = 1:size(directions, 1)\n for j = i+1:size(directions, 1)\n % Check if direction vectors are parallel\n cross_product = directions(i, 1) * directions(j, 2) - directions(i, 2) * directions(j, 1);\n if abs(cross_product) &lt; threshold\n parallel_pairs = [parallel_pairs; i, j]; % Store indices of parallel segments\n end\n end\nend\n\n% Display parallel line segments\ndisp('Parallel line segments (by indices):');\ndisp(parallel_pairs);\n\n% Create figure\nfigure;\nhold on;\ngrid on;\naxis equal;\nxlabel('X-axis');\nylabel('Y-axis');\ntitle('Line Segments Plot');\n\n% Plot each line segment\nfor i = 1:size(line_segments, 1)\n x = [line_segments(i, 1), line_segments(i, 3)];\n y = [line_segments(i, 2), line_segments(i, 4)];\n plot(x, y, 'o-', 'LineWidth', 2, 'MarkerSize', 8, 'MarkerFaceColor', 'b');\nend\n\nlegend('Line Segments');\nhold off;\n</code></pre>\n<p>I found <strong>parallel_pairs</strong> is empty. - What is the wrong in my code? How could I implemented it correctly?</p>\n<p>Thank you.</p>\n"^^ . . . . "0"^^ . "0"^^ . . . . . . "1"^^ . . "Error in ode45 and 'Events' of a Satellite Tracking Radar Model (MATLAB)"^^ . "@Anonymous I've already tried that method but something is not working well."^^ . . "0"^^ . . . . . . . . "Thanks for following up on my answer! Note that I used different points to define the objects. For legibility, I just used ints below 10 to define the planes. Even when I plug in the original values, however, my version returns different distances. This is due to errors in your `plane_points_to_coeffs` function. In defining x1, x2...z2,z3, there is a typo with y3: it should be `y3 = C(2)`."^^ . "The [MATLAB documentation](https://www.mathworks.com/help/matlab/ref/rgb2gray.html#buiz8mj-9) gives the coefficients used by `rgb2gray`, which are different from those in your code."^^ . "2"^^ . . . . . . "0"^^ . . . . . . . . . . "geometry"^^ . "2"^^ . "<p>The (<em>i</em><sub> </sub>,<sub> </sub><em>j</em>)-th entry of the result matrix <strong>C</strong> can be seen as the vector product, without conjugation, of the <em>i</em>-th row of <strong>A</strong> (transposed) and the <em>j</em>-th column of <strong>B</strong>. So you can get all pairs of indices (<em>i</em><sub> </sub>,<sub> </sub><em>j</em>) from <strong>L</strong> and do that in a vectorized way:</p>\n<pre><code>% Example data:\nm = 3; n = 4; v = 9;\nL = logical([0 0 1 0; 0 1 1 0; 1 0 0 0]); % m by n\nA = rand(m, v);\nB = rand(v, n);\n\n% Computation:\n[ii, jj] = find(L); % all pairs for which the result is needed\nC = sparse(m, n); % preallocate as sparse\nind = ii + (jj-1)*m; % linear index from ii and jj\nC(ind) = sum(A(ii,:).'.*B(:,jj), 1); % actual computation\n</code></pre>\n<p>If you only need a vector containing the relevant entries of <strong>C</strong>, instead of the whole matrix:</p>\n<pre><code>% Computation:\n[ii, jj] = find(L); % all pairs for which the result is needed\nind = ii + (jj-1)*m; % linear index from ii and jj\nc = sum(A(ii,:).'.*B(:,jj), 1); % actual computation\n</code></pre>\n"^^ . "not sure what the overhead would be using `min(abs(x))` to make this work with any real array"^^ . "1"^^ . . "1"^^ . "0"^^ . . . . "0"^^ . . "0"^^ . . "1"^^ . "1"^^ . . . . "How do i mix theese vectors into a matrix in Matlab?"^^ . "MATLAB runs significantly slower after storing value in a global search"^^ . "0"^^ . . . . . . . "Shouldn't you be importing the XML and Exporting to XML? Your code is reading the stl."^^ . "0"^^ . . "4"^^ . . . "1"^^ . . . "<p>I found the problem:</p>\n<p><a href="https://i.sstatic.net/e9z8AfvI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/e9z8AfvI.png" alt="Application properties" /></a></p>\n<p>the bitness of the application is forced to 32bit even if the AnyCPU model is applied if this checkbox is checked (it translate to <strong>Perfer 32bit</strong>)</p>\n"^^ . "0"^^ . "0"^^ . . . "0"^^ . . "0"^^ . . . . "0"^^ . "As Tim says, please identify your camera and how it is connected. Likewise, please state your OS."^^ . . . "<p>I am running two live scripts, let's call them <code>main.mlx</code> and <code>sub.mlx</code>. Below are MWEs.</p>\n<p>The <code>main.mlx</code>:</p>\n<pre><code>dbstack().file\nsub\n</code></pre>\n<p>The <code>sub.mlx</code></p>\n<pre><code>dbstack().file\n</code></pre>\n<p>When running <code>dbstack().file</code> in a live script, a file name &quot;LiveEditorEvaluationHelper(randomNumbers).m&quot; is returned. If <code>sub.mlx</code> is run manually, it returns a different Live Editor file name than when <code>main.mlx</code> is run (which it should). When <code>sub.mlx</code> is called through <code>main.mlx</code> though, the same Live Editor file name is returned twice, which is obviously incorrect.</p>\n<p>I need to be able to get the &quot;LiveEditorEvaluationHelper(randomNumbers).m&quot; from sub through main. I have multiple subscripts, and the &quot;LiveEditorEvaluationHelper(randomNumbers).m&quot; changes everytime MATLAB is restarted, so running it once and then just saving the name as a variable is very impractical. Using</p>\n<pre><code>f = matlab.desktop.editor.getActiveFilename\n</code></pre>\n<p>also doesn't work, since the &quot;active file&quot; is <code>main.mlx</code>. I am assuming just calling <code>sub.mlx</code> through <code>main.mlx</code> doesn't activate the script, or at the very least isn't interpreted as a function, so it isn't added on the dbstack struct, but I can't seem to find a way around this. I have seemingly looked everywhere, and can't find an answer to this. I apologize in advance if the solution to this is glaringly obvious. Thanks for your help!</p>\n<p>--- <strong>SOME CONTEXT</strong> ---</p>\n<p>For educational purposes, I need to write my code in Live Scripts, where I have a script to simulate physical phenomena. This is divided up into subscripts based on parts of the simulation. I need to use the Live Script to be able to explain what several functions do and how they work. Some of these functions are in subscripts, but are also used in the main script. My main goal is thus to be able to call a function that is declared in a different live script, instead of in the script itself or in a separate <code>.m</code> function file. Bear with me, chaos is about to ensue. Just executing the subscript in the <code>main.mlx</code> like</p>\n<pre><code>sub\n</code></pre>\n<p>doesn't allow for subscript functions to be saved in the workspace, and thus can't be called in the main script. A work-around for this is creating <code>myFunction.m</code> in the same folder instead, so I can call the function in <code>main.mlx</code> that way. However, that only statically works when <code>myFunction.m</code> doesn't change. That's not the case: I want to be able to alter the function code in <code>sub.mlx</code> (where explanations, LaTeX equations and figures are present), and then dynamically update <code>myFunction.m</code> in the background, so that <code>main.mlx</code> can now call the updated function &quot;seemingly&quot; from <code>sub.mlx</code>. The algorithm I wrote to do this works perfectly if I <em>manually</em> run <code>sub.mlx</code>. However, if I then execute <code>sub.mlx</code> through <code>main.mlx</code>, the function doesn't work anymore. Find the code below. I have a strong feeling as to why this fails.</p>\n<pre><code>function saveFunction(functionName)\n stack = dbstack; % Get the current script filename and line number\n scriptName = stack(2).file; % The file where the function is called\n \n % Open the script file\n fid = fopen(scriptName, 'r');\n if fid == -1\n error('Cannot open the file: %s', scriptName);\n end\n \n % Initialize variables to track lines\n currentLine = stack(2).line; % The line where the function is called\n linesToSave = {};\n foundFunction = false;\n \n % Read the file and move upwards, starting just above the current line\n lineNumber = currentLine - 1;\n while lineNumber &gt; 0\n % Read the current line\n lineNum = 1;\n fseek(fid, 0, 'bof'); % Reset fgetl\n while lineNum &lt; lineNumber\n fgetl(fid); % Skip the lines until the target line\n lineNum = lineNum + 1;\n end\n tline = fgetl(fid);\n \n % Check if we found a 'function' keyword in this line\n if contains(tline, 'function')\n foundFunction = true;\n linesToSave{end+1} = tline; % Save the line with 'function'\n break; % Stop since the full function definition has been found\n end\n \n % Add the line to the linesToSave list\n linesToSave{end+1} = tline;\n \n % Decrease the line number to move upwards\n lineNumber = lineNumber - 1;\n end\n \n % Close the file\n fclose(fid);\n \n % If no function was found, raise an error\n if ~foundFunction\n error('No function definition found in the script before the call.');\n end\n \n % Save the collected lines to a text file with the functionName\n fileID = fopen(['Functions/', functionName, '.m'], 'w');\n if fileID == -1\n error('Cannot create the file: %s.m', functionName);\n end\n \n % Write the lines to the text file\n for i = length(linesToSave):-1:1\n fprintf(fileID, '%s\\n', linesToSave{i});\n end\n \n % Close the output file\n fclose(fileID);\n \n disp(['Code saved successfully as Functions/', functionName, '.m']);\nend\n</code></pre>\n<p>Provided a folder &quot;Functions&quot; already exist in the current folder and is added to the path, the function is called like</p>\n<pre><code>% a function in sub.mlx\nfunction a = myFunction(b, c)\n a = b + c;\nend\nsaveFunction('myFunction');\n</code></pre>\n<p>where it looks for the closest function above where it was called, and saves it accordingly. (Yes, I know this won't work with nested functions, that's fine.) As I said, this works beautifully when running <code>sub.mlx</code>. When executed through <code>main.mlx</code> though, the active file is <code>main.mlx</code>, not <code>sub.mlx</code>, and <code>sub.mlx</code> (and the actual <code>.m</code> file running in the background, &quot;Live Editor Helper ...&quot;) is not added to dbstack. So, <code>stack</code>, <code>scriptName</code> and <code>currentLine</code> fail to deliver what they should. I have tried to alter this algorithm to make it work, but can't seem to fix it. Any help is welcome!</p>\n"^^ . "How to extend linearly independent vectors in the null space of a matrix to a basis of the null space with Matlab"^^ . "1"^^ . . . "0"^^ . . . . "How can I change my code to more accurately determine the damping matrix?"^^ . "1"^^ . . . "Why are you not using [`padarray`](https://www.mathworks.com/help/images/ref/padarray.html#d126e259129)? If you're intent on implementing this yourself, why are you not using matrix indexing rather than loops?"^^ . . . . . "What is the box constraint in the output of a support vector machine in matlab?"^^ . . "1"^^ . . "0"^^ . "0"^^ . "2"^^ . . "<p>I need to create a .NET assembly from a Matlab 2019b 64bit script and use it in .NET 4.8 application wrote in Visual Studio 2022 64bit .\nThe script is pretty simple:</p>\n<pre class="lang-matlab prettyprint-override"><code>function [SNR, PhaseNoise] = Measure_SNR_w_SBX(FullName, FigurePath)\nclose all\n%%Do something with data in file FullName, calculate SNR, PhaseNoise and\n%%create a file FigurePath img\nend\n</code></pre>\n<p>I created the assembly trough this command:</p>\n<pre><code>mcc -W 'dotnet:myAssembly,myClass' -T link:lib Measure_SNR_w_SBX.m\n</code></pre>\n<p>resulting in an assemply exposing, among others, this method:</p>\n<pre class="lang-cs prettyprint-override"><code>public MWArray[] Measure_SNR_w_SBX(int numArgsOut, MWArray FullName, MWArray FigurePath)\n{\n return mcr.EvaluateFunction(numArgsOut, &quot;Measure_SNR_w_SBX&quot;, FullName, FigurePath);\n}\n</code></pre>\n<p>The final usage will be an application where I cannot use MWArray or other Matlab types but I'm restricted to standard type (double, strings) so I defined a wrapper assemlby (.NET 4.8) that uses standard types parameters:</p>\n<pre class="lang-cs prettyprint-override"><code>public void Measure_SNR_w_SBX(in string FullName, in string FigurePath, out double SNR, out double PhaseNoiseMean)\n{ \n MWCharArray mwFullName = new MWCharArray(FullName);\n MWCharArray mwFigurePath = new MWCharArray(FigurePath);\n \n MWNumericArray output = obj.Measure_SNR_w_SBX(2, mwFullName, mwFigurePath);\n \n SNR = output[0].ToScalarDouble();\n PhaseNoiseMean = output[1].ToScalarDouble();\n}\n</code></pre>\n<p>Inside the wrapper I instantiate the Matlab produced assembly trough this:</p>\n<pre class="lang-cs prettyprint-override"><code>using myAssembly;\nusing MathWorks.MATLAB.NET.Arrays;\n[....]\nobj = new myAssembly.myClass();\n</code></pre>\n<p>But when myClass is istantiated what I got is:</p>\n<pre><code>System.TypeInitializationException: 'The type initializer for 'myAssembly.myClass' threw an exception.'\n</code></pre>\n<p>which in turn collect three internal exceptions:</p>\n<pre><code>TypeInitializationException: The type initializer of 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception.\nTypeInitializationException: The type initializer of 'MathWorks.MATLAB.NET.Arrays.MWArray' threw an exception.\nBadImageFormatException: Attempt to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)\n</code></pre>\n<p>Of course myAssembly, mwArray and wrapper assemblies are referenced into the application.\nMatlab runtime is installed and the Array assembly is placed here:</p>\n<pre><code>C:\\Program Files\\MATLAB\\MATLAB Runtime\\v97\\toolbox\\dotnetbuilder\\bin\\win64\\v4.0\\MWArray.dll\n</code></pre>\n<p>Also excluding the wrapper assembly and instantiating myAssembly directly into the application lead to the same result.\nAnd if I change the call order i.e.:</p>\n<pre class="lang-cs prettyprint-override"><code>MWCharArray fullName = new MWCharArray(txtDatFile.Text);\nMWCharArray figure_path = new MWCharArray(txtFigureFile.Text);\nvar obj = new myAssembly.myClass();\noutput output = obj.Measure_SNR_w_SBX(2, fullName, figurePath);\ndouble snr = output[0].ToScalarDouble();\ndouble phase_noise = output[1].ToScalarDouble();\n</code></pre>\n<p>The exception is thrown on the first line:</p>\n<pre><code>MWCharArray fullName = new MWCharArray(txtDatFile.Text);\n</code></pre>\n<p>i.e.:</p>\n<pre><code>System.TypeInitializationException: 'The type initializer of 'MathWorks.MATLAB.NET.Arrays.MWArray' threw an exception.'\n</code></pre>\n<p>that's collecting:</p>\n<pre><code>BadImageFormatException: Attempt to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)\nTypeInitializationException: The type initializer of 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception.\n</code></pre>\n<p>How can I fix this?</p>\n"^^ . "<p>I am rewriting some Code that is written in Matlab to C++ with the usage of EIGEN (in Windows 10, Visual Studio 2022). In one particular case I am having a huge performance drop with EIGEN which I am not able to fix.</p>\n<p>A minimal example is the following in Matlab:</p>\n<pre><code>r = [1,2,3,4,5];\ninit = ones(9, 1);\nM = zeros(9, 5);\n\ntic\nfor i = 1:1E6\n M = repmat(init, [1, length(r)]);\n M = r.*M + init;\nend\ntoc\n\n&gt;&gt; Elapsed time is 0.605376 seconds.\n</code></pre>\n<p>In words: I am first replicating the column vector <code>init</code> to fill the matrix <code>M</code>. Then I am multiplying a row vector <code>r</code> elementwise to <code>M</code> and add <code>init</code> to it.</p>\n<p>My C++ Version looks like this:</p>\n<pre><code>RowVector&lt;double, 5&gt; r = { 1.0, 2.0, 3.0, 4.0, 5.0 };\nVector&lt;double, 9&gt; init = {};\ninit.setOnes();\nMatrix&lt;double, 9, 5&gt; M = {};\n\nstd::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();\nfor (int i = 0; i &lt; 1E6; i++) {\n M = init.replicate(1, r.size());\n\n M.array().rowwise() *= r.array();\n M.array().colwise() += init.array();\n}\nstd::chrono::steady_clock::time_point terminate = std::chrono::steady_clock::now();\n\nstd::cout &lt;&lt; &quot;Duration:&quot; &lt;&lt; std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(terminate - start).count() &lt;&lt; &quot;[ms]&quot; &lt;&lt; std::endl;\n\n&gt;&gt; Duration:13130[ms]\n</code></pre>\n<p>Obsiously Matlabs Version is way smarter than my C++ Version. What am I doing wrong? I guess it could have something to do with MKL which is used by Matlab. I installed MKL as well and it doesn't seem to have a performance impact at all in this case.</p>\n"^^ . "@3CxEZiVlQ : I just added the correct tag."^^ . . "3"^^ . . "1"^^ . . . "0"^^ . . "0"^^ . "1"^^ . . . . "1"^^ . "1"^^ . "0"^^ . "By the way, MATLAB has two releases per year, so the “a” or “b” in the release name is important. There is potentially as much difference between R2024a and R2024b as between R2024b and R2025a."^^ . "eigen"^^ . . . "0"^^ . "file"^^ . . "0"^^ . . "0"^^ . . "0"^^ . . . "0"^^ . "@StephenC This is obviously not true https://de.mathworks.com/help/matlab/matlab_external/passing-data-to-java-methods.html I think you can normally mix java and matlab"^^ . . . . . "3"^^ . "0"^^ . "0"^^ . . . . . "Thank you very much for your reply. I was thinking that maybe I'm not using Matlab's commands correctly. I'll still leave the question open for the time being, because one gets the feeling that I'm not the first to encounter this problem."^^ . . . . . . . . . "2"^^ . "2"^^ . . "0"^^ . . . . "0"^^ . ""it is not working correctly": Please provide details."^^ . . "Solving Differential Equations in MATLAB's Symbolic Math Toolbox"^^ . "multidimensional-array"^^ . "1"^^ . . . . . "1"^^ . . "Solid approach -- but do you think there would be a more efficient way using the 'periodicity' of L? For instance if L had the same number of ones in each row and column, you could potentially get the rows and columns needed and just do `C_tmp = A(rows,:)*B(:,cols)` before "expanding" `C_tmp` into `C`. But in the absence of a precise relationship like that, is there any other way to use the regular nature of `L` to speed things up?"^^ . . . . . . "Sorry, I corrected the points. Each A,B,C point is located in the same object. I want to use one of the groups of three points to create a plane. and then from point A of the other group, calculate the smallest distance to the plane and plot it."^^ . . . "0"^^ . "0"^^ . . "1"^^ . "<p>I have a simple Simulink model that passes a constant variable to the workspace.\n<a href="https://i.sstatic.net/ip2AfCj8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ip2AfCj8.png" alt="enter image description here" /></a></p>\n<p>I've converted the Simulink model to an <strong>exe-file</strong> using <strong>Simulink Coder</strong> (with <strong>grt.tlc</strong> as the target system file). However, I'm struggling to <strong>change the value of the constant myConstantValue and send it to the executable file</strong>. I don't want to compile every time when I want to change the value.</p>\n<p>I've tried several options, such as saving the new myConstantValue in a .mat file and calling it in MATLAB with <strong>system('MyModel.exe -p myConstantValue.mat')</strong>, or writing myConstantValue=100 to a .txt file and calling it with <strong>system('MyModel.exe -i input_params.txt')</strong>. Unfortunately, none of these methods work—the executable always uses the initial data.</p>\n<p>I've also tried changing various settings in the Code Generation settings of Simulink, such as setting the default parameter behavior to &quot;Tunable&quot;, but this hasn't made any difference.</p>\n<p>Could you please help me figure out how to change the constant value and pass it to the executable file?</p>\n"^^ . "You didn't state the camera make and model."^^ . "matlab-deployment"^^ . . . . . . . . . "1"^^ . . . "computer-vision"^^ . "0"^^ . . "<p>It would make it slightly easier if the column headings in your Excel table were valid MATLAB names, so that they stay the same when read in as MATLAB table headers. Then you can simply read it in with <a href="https://www.mathworks.com/help/matlab/ref/readtable.html" rel="nofollow noreferrer"><code>tbl = readtable( 'mytable.csv' );</code></a> you can use this function with <code>xlsx</code> files too, optionally setting the sheet name and range to read.</p>\n<p>Then you could assign all of the variables to your workspace with something like</p>\n<pre><code>% Loop over rows of the table\nfor ii = 1:height(tbl)\n % assign variable to base workspace\n assignin( 'base', tbl.ParameterName{ii}, tbl.ParameterDefaultValue(ii) );\nend\n</code></pre>\n<p>It's often easier to manage your data if you have it in the model workspace, or at least a <code>struct</code> rather than lots of &quot;loose&quot; variables, but this should work if you just want something to let you quickly parameterise from your Excel table.</p>\n"^^ . . "alias"^^ . "Please read [ask] and how to provide a [mcve]. Right now you haven't provided anything but a general description and requirement."^^ . "0"^^ . . . . "1"^^ . . "0"^^ . "@Wolfie I tested both with R2022b and R2024b and both with `figure` and `uifigure` (same issue in all cases). I edited question accordingly."^^ . . "unpivot"^^ . . "Hi @Wolfie! I have appended some context to my question, I concede that this is probably quite a niche topic, or there might exist better ways to achieve what I'm trying to achieve. Any help is welcome!"^^ . . . . . "How can I calculate the output frequency steps of the rpmfreqmap function in matlab"^^ . "So reading between the lines, there is no way to get the 14bit raw data from the camera into Mathlab (a bit rubbish). Configuring the camera as 8bit is what I currently do, but I am losing half the data. So the short answer answer to the posted question is "no", irrespective of the camera etc."^^ . . . "0"^^ . . "<p>You can set the default figure position using</p>\n<pre><code>set(groot, 'DefaultFigurePosition', [x, y, width, height])\n</code></pre>\n<p><sup>Ref this MATLAB Answers question: <a href="https://uk.mathworks.com/matlabcentral/answers/526580-change-de-default-position-of-plot" rel="nofollow noreferrer">https://uk.mathworks.com/matlabcentral/answers/526580-change-de-default-position-of-plot</a></sup></p>\n<p>You could set this on startup, or before you run some code, and optionally reset it when you're done (I believe it will reset on MATLAB restart anyway). You can get the position before changing it with <code>pos = get(groot, 'DefaultFigurePosition');</code>, you could also use the existing default to preserve the <code>width</code> and <code>height</code> whilst changing <code>x</code> and <code>y</code>.</p>\n"^^ . "0"^^ . "0"^^ . "find"^^ . . . "<p>I have created a code to obtain the stiffness and damping matrix of a bearing system using simulated data as the input. The stiffness matrix is giving reasonably accurate results but the damping matrix is way off. I have spent days trying to diagnose the problem but cant seem to figure it out. I am using the time-domain method and using the built in lsqcurve function in MATLAB and the equation shown <a href="https://i.sstatic.net/tCenB6xy.png" rel="nofollow noreferrer">equation to determine K and X</a> where V is found using differentiation and displacement is given data input.</p>\n<pre><code>%% Load Time History Data \ndata = load('simdata.mat'); \n\n% Time vector\ntime = data.toutseconds_captured(:);\n\n% Measured dynamic forces (Fx, Fy)\nFx = data.FBh_dynamic_from_MB(:);\nFy = data.FBv_dynamic_from_MB(:);\nF_measured = [Fx, Fy]; \n\n\n%% Compute Velocities by Integration \nfsamp = 10e3; % Sampling frequency (should be sufficiently high)\nttesti = 0:1/fsamp:time(end); % Define uniform time grid\n\n% Interpolate acceleration signals for finer resolution\nXx_interp = interp1(time, data.xBrelJ_dynamic, ttesti);\nXy_interp = interp1(time, data.yBrelJ_dynamic, ttesti);\nX = [Xx_interp; Xy_interp];\n\n% Compute velocity by numerical integration\ndt = mean(diff(ttesti));\nVx = [0, diff(Xx_interp) / dt]; \nVy = [0, diff(Xy_interp) / dt];\nV = [Vx(:), Vy(:)]';\n\n% Interpolate force signals to match uniform time step\nFx_interp = interp1(time, data.FBh_dynamic_from_MB, ttesti);\nFy_interp = interp1(time, data.FBv_dynamic_from_MB, ttesti);\nF = [Fx_interp(:), Fy_interp(:)];\nF = F(:);\n\n% Initial guess for parameters (8 elements: 4 for C, 4 for K)\nparams_initial = [300 100 100 300, 10e3 10 10 10e3]'; % Initial guess for K\n\n% Define the model function\nforce_model = @(params, input_data) compute_predicted_force(params, input_data);\n\n% Use lsqcurvefit to estimate parameters\noptions = optimoptions('lsqcurvefit','Display','iter'); % Display iteration inf\n\n% Combine displacement and velocity into a single input array\ninput_data = [X', V']; \n\nparams_estimated = lsqcurvefit(force_model, params_initial, input_data, F, [], [], options);\n\n% Extract estimated matrices\nC_est = reshape(params_estimated(1:4), [2,2]); % Damping matrix\nK_est = reshape(params_estimated(5:8), [2,2]); % Stiffness matrix\n\ndisp('Estimated Damping Matrix (C):');\ndisp(C_est);\ndisp('Estimated Stiffness Matrix (K):');\ndisp(K_est);\n\n\n%% Function to Compute Predicted Forces\nfunction F_est = compute_predicted_force(params, input_data)\n\n X = input_data(:, 1:2)';\n V = input_data(:, 3:4)';\n\n C = reshape(params(1:4), [2,2]); % Extract damping matrix (2x2)\n K = reshape(params(5:8), [2,2]); % Extract stiffness matrix (2x2\n\n\n F_est = (K * X) + (C * V);\n\n % F_est: column vector for lsqcurvefit\n F_est = F_est';\n F_est = F_est(:);\nend\n</code></pre>\n<p>This is the code I have thus far and the outputs are <a href="https://i.sstatic.net/nTODAUPN.png" rel="nofollow noreferrer">current damping and stiffness matrix</a> however the results I am hoping to be closer to are <a href="https://i.sstatic.net/wjkni5vY.png" rel="nofollow noreferrer">accurate stiffness and damping matrix</a>, thanks</p>\n<p>Additionally, these are the frequency domain analysis graphs produced for force in X and Y direction. <a href="https://i.sstatic.net/Z4oIXzOm.png" rel="nofollow noreferrer">Freq-domain analysis - Y direction</a>. <a href="https://i.sstatic.net/65rNDSCB.png" rel="nofollow noreferrer">enter Freq-domain analysis - x direction description here</a></p>\n"^^ . "Causality error in PLL linearization simulink"^^ . "Reposting Bill's comment from proving ground: _"How big are m, n, and v? It will be hard to beat A*B. If you compute C = A*B you can index the values you seek with D = C(L) if L is logical, or D=C(logical(L)) if L is numeric containing 0s and 1s"_"^^ . . "<p>I need to solve one LP per thread at the same time.</p>\n<p>I'm coding in Matlab and using gurobi as a solver. Since gurobi is an API that actually run calculations in C++, I'm unable to use several threads at the same time, despite that Simplex be a single thread algorithm. I tried the parfor function, but I got the MEX function error (&quot;<em>Use of MEX functions is not supported on a thread-based worker.</em>&quot;).</p>\n<p>I would like to highlight that those LP are similar and I can't build one big problem with all of them since some can be infeasible. So, build one big LP and solving using barrier (which is multithread) is not an option.</p>\n<p>Is there any way (using gurobi or something else, even other programming language) to handle that?</p>\n<p>I tried to solve that using parallel toolbox from Matlab, however, since gurobi is a MEX function, I'm unable to assign one thread to each LP simultaneously. I would like to know if someone knows a way to do that, even if it using other programming language and/or solver.</p>\n"^^ . . . "Yes, you're looping through that list. But you're not indexing into the matrix, you're only looking at the array of indices. To index into a sparse matrix you need to do a binary search on the array of column indices, then a binary search on the array of row indices for that column. Finally, if your desired element is there, you need to read in array that stores the values to find the result of the indexing operation."^^ . "0"^^ . "0"^^ . . . . . . . . "Matlab: how to unstack a table and filter reslting matrix"^^ . . . "0"^^ . . "1"^^ . "0"^^ . "As an aside: `setx PATH "$env:Path;..."` is best avoided for persistent updates: while it _may_ have no (immediate) ill effects, it definitely _can_: `setx.exe` has a hard 1024-character limit, and replaces the original `REG_EXPAND_SZ` value with a `REG_SZ` value if the new value happens not to contain _unexpanded_ environment-variable references. Additionally, you're _duplicating entries_ by basing your new value on the process-level value of `$env:Path`, which is a _composite_ of the system-level and the user-level definition and only contains _expanded_ values."^^ . . "<p>You can try using the &quot;Matlab in VSCode&quot; extension (shinyypig.matlab-in-vscode) along with the official MathWorks extension, which will allow you to run the active cell.</p>\n<p>Excerpt from the official extension documentation. Check <a href="https://github.com/shinyypig/matlab-in-vscode" rel="nofollow noreferrer">this</a> for more information.</p>\n<blockquote>\n<p>Cell Mode</p>\n<p>You can split your code by %%, click the run cell button, or simply press ctrl+enter (Mac: cmd+enter) to run the active cell.</p>\n</blockquote>\n"^^ . . "symbolic-math"^^ . "Pre-allocating as a full matrix would make this faster, if it fits in memory."^^ . . . . . . . "<p>I'm trying to apply the Grad Cam technique to a 3D CNN (ResNet101). To do this, I'm trying to use the following code:</p>\n<pre><code>dlImg = dlarray(single(img), 'SSSCB');\n\nsoftmaxName = 'sofctmax'; \nfeatureLayerName = 'res5c_relu';\n\ndlScores = predict(dlnet, dlImg); \nYPredScores = extractdata(dlScores)';\n[score, classIdx] = max(YPredScores, [], 2);\n\nclassfn = categorical(classIdx, 1:numel(categories(YTrue)), categories(YTrue));\n\n[featureMap, dScoresdMap] = dlfeval(@gradcam, dlnet, dlImg, softmaxName, featureLayerName, classfn);\n\nfunction [featureMap,dScoresdMap] = gradcam(dlnet, dlImg, softmaxName, featureLayerName, classIdx) \n\n[scores,featureMap] = predict(dlnet, dlImg, 'Outputs', {softmaxName, featureLayerName}); \nclassScore = scores(classIdx); \nclassScore = extractdata(classScore); \ndScoresdMap = dlgradient(classScore,featureMap); \nend\n</code></pre>\n<p>But I get this error in the <code>dlfeval</code> line: <code>Arrays have incompatible sizes for this operation</code>. If I run only my gradcam function the error changes because of dlgradient: Value to differentiate is not a dlarray. It must be a traced real dlarray scalar.\nMy classScore is a single number and my featureMap is a 5-D dlarray witha size of 7 7 1 2048 1.</p>\n<p>What am I doing wrong?\nThanks in advance.</p>\n"^^ . . "you're assuming I'm deploying data togheter with matlab script executable ... this's not what's happening.. I simply need to know where the exe is located because this will be the folder where data are actually deployed."^^ . . "1"^^ . . . . . . . . . "How it is possible to solve one LP (Simplex) per thread in parallel?"^^ . "@Yunnosch You are all right! SO SORRY! I am not that pro! (but humble enough ;-) )"^^ . "MATLAB: How to calculate the distance between a plane and a point"^^ . "histogram"^^ . "arrays"^^ . . . "-1"^^ . . . "the output is not going to standard output. Try without the -r which creates a report (file)."^^ . . "0"^^ . . . . "0"^^ . . "0"^^ . "0"^^ . . . . . "Is it possible to have a block with multiple outputs which also calls C code in Matlab Simulink?"^^ . "1"^^ . "0"^^ . . . . "0"^^ . . . . . . . . "1"^^ . . "0"^^ . "Registration/alignment of two medical data STL files in Matlab"^^ . . . . . . . "c++"^^ . "<p>When you construct a <code>table</code>, the table variables only pick up the names from the names of the input workspace variables if you don't perform an operation on those input workspace variables. (In that case, you're effectively passing in to the <code>table</code> constructor unnamed temporary arrays).</p>\n<p>You can either:</p>\n<ol>\n<li><p>Operate on the arrays up-front and store them back in named variables that you pass directly to the <code>table</code> constructor, or</p>\n<pre class="lang-matlab prettyprint-override"><code>Radii = Radii';\nSurfaceA = SurfaceA';\nVolume = Volume';\nSphere3 = table(Radii,SurfaceA,Volume)\n</code></pre>\n</li>\n<li><p>Use the name-value argument <code>VariableNames=[&quot;Radii&quot;, &quot;Surface A&quot;, &quot;Volume&quot;])</code></p>\n<pre class="lang-matlab prettyprint-override"><code>Sphere2 = table(Radii', SurfaceA', Volume', ...\n VariableNames=[&quot;Radii&quot;, &quot;Surface A&quot;, &quot;Volume&quot;])\n</code></pre>\n</li>\n</ol>\n"^^ . . "0"^^ . "chocolatey"^^ . "matlab-app-designer"^^ . . . . "1"^^ . . . . . . "0"^^ . "0"^^ . "Ohhhh... I see. Thank you! That makes a lot of sense :)"^^ . . "1"^^ . "If the performance is important consider generating the 3D arrays in the form of `[binNum * xdim * ydim]` and `[maxElementNum * xdim * ydim]` for `input_hist` and `output_values` respectively. In this case there is no need to perform permute and ipermute."^^ . . . "1"^^ . "0"^^ . . "2"^^ . . "2"^^ . . . "<pre><code>% A(2,2) A(2,1) A(2,1) A(2,2) A(2,3) A(2,3) A(2,2) \n% A(1,2) A(1,1) A(1,1) A(1,2) A(1,3) A(1,3) A(1,2)\n% 0 0 1 2 3 0 0\n% 0 0 4 5 6 0 0\n% 0 0 7 8 9 0 0\n% A(3,2) A(3,1) A(3,1) A(3,2) A(3,3) A(3,3) A(3,2) \n% A(2,2) A(2,1) A(2,1) A(2,2) A(2,3) A(2,3) A(2,2)\n</code></pre>\n<p>Hello, I am working on implementing symmetric padding using a for loop in MATLAB. However, it is not working correctly, so I have a question.</p>\n<p>Matrix A is a 3×3 matrix, and P is a 7×7 matrix. I want to map the coordinates of A to P, filling the values in P according to this diagram of padman, starting from P(1,1) to P(1,7).</p>\n<p>Could you please help me with how to implement this? Thank you!</p>\n<pre><code>A=[1, 2, 3; 4, 5, 6; 7, 8, 9]\nsize = size(P,1)\nm=2 %padding size\n\nfor i = 1 : m %upper\n for j= 1 : size\n P(i,j) = A( )\nend\nend\n\n\nfor i= 1 : m %down\n for j= 1 : size\n P(i+size-m,j) = A( )\nend\nend\n</code></pre>\n"^^ . . "0"^^ . "2"^^ . "0"^^ . "0"^^ . "0"^^ . "Hi Ferror, thank you for your answer. \nBut it is still not working. The command set_param cannot call the exe-file, and if I use the command system('test.exe -p constantValue.mat') % I save the new value of myConstantValue inside the mat-file.\n\nI still only get the initial value that has been used to compile the Simulink model."^^ . . "1"^^ . . "Also, why are the values to the left and to the right of the central matrix zeros rather than than the reflected values?"^^ . "0"^^ . . "Incoherence when using Matlab's lsim regarding continuous and discretized transfer function models"^^ . . . "Find the page in a 3D matrix that is closest to a given matrix"^^ . "<p>When using sparse matrices, it's easy to find non-zero entries quickly (as these are the only elements stored). However, what's the best way to find the first ZERO entry? Using approaches like <code>find(X==0,1)</code> or <code>find(~X,1)</code> tend to be slow as these require the negation of the whole matrix. It doesn't feel like that should be necessary -- is there a better way?</p>\n<hr />\n<p>For instance, naively iterating over the array seems to be slightly faster than using <code>find(X==0,1)</code>:</p>\n<pre><code>% Create a sparse array [10% filled]\nx = sparse(5000,1);\nx(randsample(5000,500)) = 1;\nnRuns = 1e5; \n% Find the first element, a million times\nidx = zeros(nRuns,1);\ntic\nfor n=1:nRuns\n idx(n) = find(x==0,1);\nend\ntoc\n\n\n%%\n% Create a sparse array [10% filled]\nx = sparse(5000,1);\nx(randsample(5000,500)) = 1;\nnRuns = 1e5; \n% Find the first element, a million times\nidx = zeros(nRuns,1);\ntic\nfor n=1:nRuns\n for kk = 1:numel(x)\n [ii,jj] = ind2sub(size(x), kk);\n if x(ii,jj)==0; idx(n) = ii + (jj-1)*n; break; end\n end\nend\ntoc\n\n</code></pre>\n<p>But what is the best way to do this?</p>\n"^^ . . . "remote-desktop"^^ . "How to create custom reinforcement learning agent in matlab and training with Simulink environment"^^ . "How to Prevent issues in a Holt-Winters Forecasting Model with High Smoothing Parameters?"^^ . "Simulation of radar images based on a simulated wave field"^^ . "exe"^^ . "Data conversion between java and matlab buggy?"^^ . . "0"^^ . "@magnesium I don't see how the structure of `L` can help. Regardless of the structure, if `L` has, say, _k_ `true` entries you need to compute `k` "vector products". I don't see how a particular distribution of those entries in `L` could help; unless they formed a rectangle, in which case everything would reduce to (sub-)matrix multiplication, but that's not the case in your problem. So, why do you think structure in `L` could help? Maybe I'm missing something. Also, when you say _potentially get the rows and columns needed_, that's what my code does, specifically with `ii` and `jj`"^^ . . "excel"^^ . . . . "0"^^ . . . . . . "0"^^ . . . . . . . . "1"^^ . "1"^^ . . "In the MathWorks coder.ceval documentation, I noticed this: ' Variables to hold nonscalar output can be passed by reference to the called C/C++ function by using coder.ref or coder.wref'. It seems that the called C/C++ function can only return a single scalar output with coder.ceval though, right?"^^ . . . . "dll"^^ . . "Your answer contains useful information, but it doesn't actually answer my question, which is a yes/no question. I prefer direct answers to questions, so they are clear and as easy to understand as possible, so if I were answering, I may include what you put in yours after first saying 'No, it is not possible to have mulitple outputs when using coder.ceval: it can only return a single, scalar output.' As it stands, I would not regard your post as having answered my question."^^ . . . . . . "0"^^ . . . "0"^^ . "@weirdgyn I'm not assuming, I'm guessing. You didn't say why you needed the directory. I also said "Don’t write to the directory where the binary is" and "Most applications store user data in a fixed directory off of the home directory". I don't know who or what deploys data to that directory, but that should be changed IMO."^^ . "1"^^ . . "<p>I am connecting <code>CCS6.2</code> to <code>Matlab2023b</code>, but I'm getting an error when I use code &quot;<strong>ticcs</strong>('boardnum',0, 'procnum', 0)&quot; to identify <code>F2812</code> board. I used it by <code>Matlab2011</code>, and I didn't have any problems. Can anyone help me, please?</p>\n<p>I want to create a CCS object in the Matlab GUI host program so that I can control the start and stop of the DSP and the transmission of data after the model is automatically generated into code.</p>\n"^^ . . "point-clouds"^^ . . "1"^^ . "Apparently (i.e. according your experimentation !) an array cell containing a Matlab Object doesn't work (i.e. appears to be empty) when passed into Java, so saying it is "allowed" in the face of other evidence is a stretch. Either way, I think this is a pointless debate. (Feel free to report this as a Matlab bug if you want to.)"^^ . . . . . . . . "1"^^ . "0"^^ . . "structure"^^ . . "<p>I'm experiencing a strange behaviour when using <code>mfilename</code> function.\nI compiled a script (<code>myScript</code>) that use <code>mfilename</code> into an executable and running it from a specific folder (<code>C:\\Users\\username\\Desktop\\appfolder\\</code>).\nI tought <code>mfilename</code> returned the full path of the executable but this's not true...\ni.e. running <code>myScript</code> executable from the above folder and printing the value returned by <code>mfilename</code> I got:</p>\n<pre><code>C:\\Users\\username\\AppData\\Local\\Temp\\username\\mcrCache9.7\\myScriptN\\myScriptT\\myScript\n</code></pre>\n<p>Where <code>myScriptN</code> and <code>myScriptT</code> are temporary subfolders.</p>\n<p>Of course this path is totaly useless if you need to locate something that's local or relative to the binary folder.</p>\n<p>Is there a function that can return the correct path when the script is executed <strong>compiled</strong>.\nBTW the same issue is found also when script are compiled into DLL or .NET assemblies.</p>\n"^^ . . . . . "0"^^ . "0"^^ . "0"^^ . . . . . "communication"^^ . . "<p>It's undocumented for Matlab to permit a logical input for the Z data in contour. See the <a href="https://www.mathworks.com/help/matlab/ref/contour.html#mw_ae4f3862-78d6-4ee2-9b3a-e024868f94f8" rel="nofollow noreferrer">matlab help for contour</a> and <a href="https://www.mathworks.com/help/matlab/ref/contourc.html#mw_1d6dcf77-5722-440f-9a9e-77c417d63d49" rel="nofollow noreferrer">contourc</a>. Octave wrote its contourc to do input checking and throw an error for an incorrect input type, and that's what you're seeing. As an octave developer mentioned in <a href="https://octave.discourse.group/t/octave-contour-function-returns-an-unexpected-error-message/6242/2" rel="nofollow noreferrer">your crosspost over at the Octave help forum</a>, the best immediate path forward would be to recast all of the logical inputs coming from statements like <code>cls==1</code> as type <code>double</code>, for example:</p>\n<p><code>contour(X, Y, double(cls==1),[1,1], 'r--');</code></p>\n<p>This was previously captured in <a href="https://savannah.gnu.org/bugs/?64078" rel="nofollow noreferrer">Octave bug #64078</a> which identified a long list of plot objects that limit or improperly handle certain input types. Not all of them are necessarily expected to be expanded, as <a href="https://wiki.octave.org/Short_projects#Test_Octave_functions_for_proper_input_handling" rel="nofollow noreferrer">Octave is generally hesitant to adopt undocumented behavior as that can (and has in the past) changed without notice causing further grief years down the road, but it can be considered on a case-by-case basis</a> but at a minimum the known non-support of Matlab-undocumented behavior could be documented in Octave. This sort of compatibility seems fairly trivial, though, so it may improve in the future.</p>\n"^^ . "1"^^ . . . . . . . . . . "optimization"^^ . . "1"^^ . . . . . "0"^^ . . "<p>Consider moving the <code>i</code> loop to just wrap the <code>if</code> statement, you're doing loads of overwrites of the elements which are not dependent on <code>i</code>.</p>\n<p>Then it also becomes more obvious where to put your assignments for <code>form(x,y,z).c_top</code>, you can just do it after the <code>i</code> loop for each struct <code>c</code></p>\n<pre><code>for j=1:length(Cr)\n for m=1:length(TR)\n for k=1:length(pH)\n form(j,m,k).name = [&quot;c&quot; num2str(Cr(j)) &quot;TR&quot; num2str(TR(m)) &quot;ph&quot; num2str(pH(k))];\n form(j,m,k).Cr = Cr(j);\n form(j,m,k).Ct = Cr(j)*TR(m); % corde tip\n form(j,m,k).S = (form(j,m,k).Cr+form(j,m,k).Ct)*H/2;\n form(j,m,k).AR = H^2./form(j,m,k).S;\n\n for i = 1:N\n if (pH(k) == 0)\n form(j,m,k).c(i) = form(j,m,k).Ct*cos(phi(i))+form(j,m,k).Cr*(1-cos(phi(i)));\n elseif (yh(i) &lt; H*pH(k))\n form(j,m,k).c(i) = form(j,m,k).Cr;\n else\n form(j,m,k).c(i) = form(j,m,k).Cr+(form(j,m,k).Ct-form(j,m,k).Cr)/(H-pH(k)*H)*(yh(i)-pH(k)*H);\n end\n end\n\n form(j,m,k).c_top = form(j,m,k).c(N/2+1:end);\n form(j,m,k).c_bot = form(j,m,k).c(1:N/2);\n end\n end\nend\n</code></pre>\n"^^ . "2"^^ . . "<p>Using <code>pwd</code> instead of <code>mfilename</code> fixes everything.</p>\n"^^ . "0"^^ . . . . . "0"^^ . . . . "0"^^ . . "@n.m.couldbeanAI so far I cannot find a way to specify such option in the command line (that's generated by mbuild)"^^ . "0"^^ . . . . . . . . . . "1"^^ . . . . "Trouble with From Spreadsheet Block in Simulink"^^ . . . "Arrays can be both inputs and outputs as pointers, the limitation is having datatypes that are arrays, like "typedef double doublearray[50]". If a function uses the doublearray type in it's prototype, you need to write a wrapper."^^ . . . "Matrix Multiplication Error in MATLAB R2022 but Not in R2024 (ECEF-to-ECI Transformation)"^^ . "@beaker was hinting at that you need to preallocate the array. You are increasing the size of the array with every iteration, this takes a lot of time. Read here: https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html -- If you use the MATLAB editor, it should have put a red wriggly line under the assignment into `a`, and when you hover over it, it shows you the warning."^^ . . . . . . . . . . "<p>Note that you need a <em>function handle</em> to minimise, but that doesn't mean you have to define everything in <em>anonymous functions</em>. It might be easier to test and debug if you just write a complete function block, so you have your main function <code>g</code> which evaluates some variable-sized <code>v</code> using a predefined <code>f</code>:</p>\n<pre><code>function x = g( f, v )\n% v is an array of unknown size, the values of which should be \n% passed as separate inputs to f\n % Convert to cell so we can use {:} syntax in function call\n vc = num2cell( v );\n % Evaluate\n x = f( v{:} );\nend\n</code></pre>\n<p>Then all your anonymous function needs to do is wrap this up so that it accepts a single input</p>\n<pre><code>gf = @(s) g( f, y + s*e_i )\n[lambda,~] = fminsearch( gf, 0 )\n</code></pre>\n<p>Alternatively if you'd written the definition of <code>f</code> directly within the <code>function</code> block for <code>g</code> then you wouldn't need to define <code>gf</code> at all, you could point directly at <code>g</code> if it took a single input.</p>\n<hr />\n<p>If you have these in the same script, you would normally put the <code>function</code> block at the bottom (although <a href="https://uk.mathworks.com/help/matlab/matlab_prog/local-functions-in-scripts.html" rel="nofollow noreferrer">since R2024b</a> they <em>can</em> go anywhere)</p>\n"^^ . . "Side-note on MATLAB: `tic/toc` is not recommended for accurate timings for a multitude of reasons. Use [`timeit()`](https://www.mathworks.com/help/matlab/ref/timeit.html) instead. This circumvents several problems, mainly the start-up time of the engine and averaging out differences in run time between runs."^^ . . . "0"^^ . "0"^^ . . . . "IT++ and Matlab randomness"^^ . . "matlab-compiler"^^ . . "1"^^ . . . . . "<p>The issue is that if you want to copy and paste a curve, the best way is to manually extract the original data and then redraw it using yyaxis right in a new plot or in the same plot, instead of directly copying and pasting!</p>\n<p>You should provide some data and code to clarify your meaning. In the absence of that, let’s assume I am using the data and code below to illustrate your point, which might not be accurate, so please point it out.</p>\n<pre class="lang-matlab prettyprint-override"><code>%% Generate sample data (Permeability &amp; Impedance)\n% Assume permeability (left axis) and impedance (right axis) vary over time\nx1 = 0:0.1:10; % Time axis (permeability)\ny1 = 10*sin(x1) + x1; % Permeability data (sine wave with linear growth)\nx2 = 0:0.1:10; % Time axis (impedance)\ny2 = 5*cos(x2) + 2*x2; % Impedance data (cosine wave with linear growth)\n\n%% Step 1: Plot the original graph (left axis: permeability, right axis: impedance)\nfigure(1);\nclf;\n\n% Left axis: Permeability\nyyaxis left;\nh_permeability = plot(x1, y1, 'b-', 'LineWidth', 1.5, 'DisplayName', 'Permeability');\nylabel('Permeability (Unit)');\nylim([min(y1)-5, max(y1)+5]);\n\n% Right axis: Impedance\nyyaxis right;\nh_impedance = plot(x2, y2, 'r--', 'LineWidth', 1.5, 'DisplayName', 'Impedance');\nylabel('Impedance (Ω)');\nylim([min(y2)-5, max(y2)+5]);\n\n% Add title and legend\ntitle('Original Data: Permeability vs. Impedance');\nlegend('Location', 'northwest');\ngrid on;\n\n%% Step 2: Extract data and generate a comparison graph (copy curves to the same axis)\nfigure(2);\nclf;\n\n% Left axis: Plot two permeability curves\nyyaxis left;\nhold on;\nplot(x1, y1, 'b-', 'LineWidth', 1.5, 'DisplayName', 'Permeability 1');\nplot(x1, y1 + 8, 'b:', 'LineWidth', 1.5, 'DisplayName', 'Permeability 2 (Shifted)'); % Copy and shift\nylabel('Permeability (Unit)');\nylim([min(y1)-5, max(y1)+15]); % Adjust range to accommodate the new curve\n\n% Right axis: Plot two impedance curves\nyyaxis right;\nhold on;\nplot(x2, y2, 'r--', 'LineWidth', 1.5, 'DisplayName', 'Impedance 1');\nplot(x2, y2 * 0.6, 'r-.', 'LineWidth', 1.5, 'DisplayName', 'Impedance 2 (Scaled)'); % Copy and scale\nylabel('Impedance (Ω)');\nylim([min(y2)-5, max(y2)+5]);\n\n% Add title, legend, and grid\ntitle('Comparison: Two Permeability &amp; Two Impedance Curves');\nlegend('Location', 'northwest');\ngrid on;\n</code></pre>\n<p><a href="https://i.sstatic.net/MzFalNpB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MzFalNpB.png" alt="original" /></a></p>\n<p><a href="https://i.sstatic.net/MBnNvA7p.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MBnNvA7p.png" alt="compare" /></a></p>\n"^^ . "<p>I wrote the Matlab GUI script below in App Designer in order to select an image ROI:</p>\n<pre><code>function markROIButtonPushed(app, event)\n function allevents(src,evt)\n evname = evt.EventName;\n switch(evname)\n case{'MovingROI'}\n disp(['ROI moving previous position: ' mat2str(evt.PreviousPosition)]);\n disp(['ROI moving current position: ' mat2str(evt.CurrentPosition)]);\n pos = roi.Position;\n app.col1 = floor(pos(1)); % Column 1\n app.col2 = ceil(pos(1) + pos(3)); % Column 2\n app.row1 = floor(pos(2)); % Row 1\n app.row2 = ceil(pos(2) + pos(4)); % Row 2\n app.x1Crop = app.col1;\n app.y1Crop = app.row1;\n case{'ROIMoved'}\n disp(['ROI moved previous position: ' mat2str(evt.PreviousPosition)]);\n disp(['ROI moved current position: ' mat2str(evt.CurrentPosition)]);\n pos = roi.Position;\n app.col1 = floor(pos(1)); % Column 1\n app.col2 = ceil(pos(1) + pos(3)); % Column 2\n app.row1 = floor(pos(2)); % Row 1\n app.row2 = ceil(pos(2) + pos(4)); % Row 2\n app.x1Crop = app.col1;\n app.y1Crop = app.row1;\n end\n end\n\n imshow(app.I,'Parent', app.imageAxes);\n roi = drawrectangle(app.imageAxes);\n [app.Iy1,app.Ix1,app.Iz1] = size(app.I);\n\n addlistener(roi,'MovingROI',@allevents);\n addlistener(roi,'ROIMoved',@allevents);\n pos = roi.Position;\n app.col1 = floor(pos(1)); % Column 1\n app.col2 = ceil(pos(1) + pos(3)); % Column 2\n app.row1 = floor(pos(2)); % Row 1\n app.row2 = ceil(pos(2) + pos(4)); % Row 2\n app.x1Crop = app.col1;\n app.y1Crop = app.row1;\n \n if app.col1 &lt; 1\n app.col1 = 1;\n end\n\n if app.row1 &lt; 1\n app.row1 = 1;\n end\n\n if app.col2 &gt; app.Ix1\n app.col2 = app.Ix1;\n end\n\n if app.row2 &gt; app.Iy1\n app.row2 = app.Iy1;\n end \n end\n\n % Button pushed function: selectROIButton\n function selectROIButtonPushed(app, event)\n app.Icrop = app.I(app.row1 : app.row2, app.col1 : app.col2, :)\n disp(app.col1)\n disp(app.row1)\n app.RoiOn = true;\n app.ROISwitch.Enable = 'off';\n end\n</code></pre>\n<p>But when I wish to start to mark the ROI from the image coordinates (1,1) for the upper-left corner of the image I get this error <strong>“Index in position 2 is invalid. Array indices must be positive integers or logical values.”</strong></p>\n<p>The same issue will appear in the lower-left corner of the image (error: <strong>&quot;Index in position 1 exceeds array bounds. Index must not exceed...&quot;</strong>)?</p>\n<p>How can I solve it?</p>\n"^^ . "1"^^ . . . . . . . . . . . "0"^^ . . . . "1"^^ . . "1"^^ . "conv-neural-network"^^ . . "Your first snippet is known to be slow and hence gives a warning. Preallocate arrays if you can. The second is indeed preallocated, I doubt that can be sped-up by much. You might want to [edit] your post to a more concrete example, as this seems too much reduced. Adding the same data to multiple pages of a matrix isn't very relevant. Do you want to concatenate matrix `A` n times, or various matrices with different names? In case of the former: do explain *why* you need to do this, as this sound like an [XY problem](https://meta.stackexchange.com/q/66377/325771)."^^ . "What you describe used to be done via either `arrayfun` or `bsxfun`. Nowadays, implicit expansion might be able to take care of multidimensional arrays, though you'd need to check that. (In the sense that given an M x N x L matrix `A` and M x N matrix `B`, `A-B` might give you a result these days and even the correct one at that. Might need to `permute()` your way around to shift dimensions to their proper positions beforehand.)"^^ . . . "1"^^ . . . "plane"^^ . . . "Thermoteknix MicroCAM 3. It's not going to help the driver is what it is, and I am looking for a Matlab work around."^^ . . "<p>I would keep the row name as a column rather than an actual row name property of the table, and then you want to <code>stack</code> the data (make it a tall, &quot;stacked&quot; table) rather than <code>unstack</code> it (to make it wider).</p>\n<p>You can do something like this:</p>\n<p>Set up the example table slightly differently:</p>\n<pre><code>row_names = {'row1','row2','row3'};\ncol_names = {'col1','col2','col3','col4','col5'};\ntable_values = [0.2, 0, 0, 0.3, 0;\n 0, 0.2, 0.2, 0, 0.1;\n 0.5, 0.5, 0, 0, 0];\n\ntbl = table();\ntbl.RowName = categorical(row_names.');\ntbl_data = array2table(table_values, 'VariableNames', col_names);\ntbl = [tbl, tbl_data];\n</code></pre>\n<p>Then stack it, naming the two new columns which will be generated</p>\n<pre><code>stacked = stack(tbl, col_names, 'NewDataVariableName', 'Value', 'IndexVariableName', 'ColName' );\n</code></pre>\n<p>Then it should be trivial to filter on the <code>Value</code> column:</p>\n<pre><code>filt = stacked( stacked.Value ~= 0, : );\n\n\nfilt =\n\n 7×3 table\n\n RowName ColName Value\n _______ _______ _____\n\n row1 col1 0.2 \n row1 col4 0.3 \n row2 col2 0.2 \n row2 col3 0.2 \n row2 col5 0.1 \n row3 col1 0.5 \n row3 col2 0.5 \n</code></pre>\n<p>This would still work if you were using the RowNames property of the table, but they will get a numerical suffix to make them unique after the stacking, which isn't really what you want.</p>\n"^^ . . . "octave"^^ . "2"^^ . "1"^^ . . . . . "Thank you! I tried using ICP, but the two clouds do not overlap, and the registration is not satisfactory. Do you know how I can improve it?prove it? I added the code to the question."^^ . . "geospatial"^^ . "0"^^ . . . "2"^^ . . . "0"^^ . . . . . "<p>I want to apply <em>constrained</em> ordinary least-squares regression similar to what is done with R <a href="https://stackoverflow.com/questions/49393773/running-regression-with-constraints-on-coefficients">here</a>, but in Matlab. The documentation doesn't suggest how to accomplish this with the available routine <code>fitlm</code> (running version R2023A with the statistics and ML toolbox). Using Wilkinson notation the model <code>y ~ 1+x1+x2</code> would be fit to response column variable <code>y</code> with column covariates <code>x1</code> and <code>x2</code> as</p>\n<pre><code>tbl=table(x1,x2,y);\nm0=fitlm(tbl, 'y~1+x1+x2'); \n</code></pre>\n<p>It seems simple enough to treat <code>x2</code> as a covariate while holding <code>x1</code> fixed at some value, just subtract <code>x1*beta1</code> from <code>y</code>:</p>\n<pre><code>yp = y- x1*beta1; % beta1 is constant\ntbl=table(x2,yp);\nm1=fitlm(tbl, 'yp~1+x2');\n</code></pre>\n<p>However there is an uncertainty associated with <code>beta1</code> which needs to be propagated into <code>beta2</code>, which the above doesn't accomplish. It also feels clumsy and possibly reinvents the wheel. (1) Are there openly available utilities to do this in Matlab? (2) If not, how to perform a constrained fit ensuring the uncertainty in <code>beta1</code> is propagated into the other coefficient?</p>\n<p>Input would be <code>y</code>,<code>x1</code>,<code>x2</code>, <code>beta1</code> and <code>sbeta1</code> (standard error of <code>beta1</code>). Desired output is <code>beta2</code> and <code>sbeta2</code> plus other statistical output generated by the regression (eg standard error).</p>\n"^^ . "<p>I am using a 14bit thermal camera, but it advertises itself as YUYV. I know this is not the format the camera is using and I can decode and convert this data to the 14bit gray scale if I have the data. Matlab captures the image and then &quot;converts&quot; it to RGB or YUV to get nonsense data. I know the camera format is the root cause but I need a way round this,</p>\n<p>Is there a way to get the camera raw data in Matlab (without it being converted to YUV or RGB)?\nOr is there a way to tell Matlab to ignore the format and see it as 16bit gray (could even live with 8bit gray if all the data was there).</p>\n<p>There is little chance of the camera manufacture changing the advertised format to gray 16.\n(I have all the image add-ons if required)</p>\n<p>Exploded all doc's and add-ons, nothing there.</p>\n"^^ . . . . "Jonathan thanks for practising the art of double checking and careful reading. I have corrected the input index in the support function to turn points to coefficients. Regarding the -d the formula comes from Wiky and the -d is used in several lines so I am going to keep both options in my answer, for the question originator to have both and perhaps verify whether Wiky formula is correct or not. Thanks"^^ . . "MinGW-W64 undefined reference to `WinMain' compiling DLL"^^ . . . . . "1"^^ . "0"^^ . . "0"^^ . "<p>For positive arrays <a href="https://www.mathworks.com/help/matlab/ref/double.min.html" rel="nofollow noreferrer">min</a> is probably the fastest solution:</p>\n<pre><code>x = sparse(5000, 1);\nx(randsample(5000, 500)) = 1; \n[~, idx] = min(x);\n</code></pre>\n<p><a href="https://www.mathworks.com/help/matlab/ref/double.ismember.html" rel="nofollow noreferrer">ismember</a> can also be used:</p>\n<pre><code>[~, ind] = ismember(0, x);\n</code></pre>\n"^^ . . . . . "Please provide enough code so others can better understand or reproduce the problem."^^ . "2"^^ . "<p>If you want to break out of the <code>for</code> loop early then you should use <code>break</code></p>\n<pre><code>Flag = 0;\n\nwhile Flag == 0\n for x = 1:10\n if x == 3\n Flag = 1;\n break % Exit the 'for' loop\n end\n end\nend\n</code></pre>\n"^^ . . . "it should be easy with Matlab 1) First import xml using https://www.mathworks.com/help/matlab/import_export/importing-xml-documents.html 2) Then export to stl using https://www.mathworks.com/matlabcentral/answers/284479-how-to-export-3d-data-from-matlab-as-a-stl-or-obj-file"^^ . "2"^^ . . "@Adriaan Thank you for the comments, I've corrected the *minimum*. I have tried the direct approach with matrices and it works both for `-` and `.*` I haven't found this functionality in the documentation..."^^ . . . . "*"Data conversion between java and matlab buggy?"* - Given how mature MATLAB is, I seriously doubt it. More likely, it doesn't work the way you think it works ... and its not a bug."^^ . . "<p>I'm trying to solve a MILP problem in Matlab Optimization Toolbox. I'm encountering with problems with the product of two decision variable of my problem which are bounded.</p>\n<ul>\n<li>0&lt;= x &lt;= 60</li>\n<li>0 &lt;= y &lt;= 8760</li>\n</ul>\n<p>The product is inside the objective function that is minimization of the cost. For this reason when I tried with the method <a href="http://www.aimms.com/aimms/download/manuals/aimms3om_integerprogrammingtricks.pdf" rel="nofollow noreferrer">http://www.aimms.com/aimms/download/manuals/aimms3om_integerprogrammingtricks.pdf</a> explained here, I obtained a value always equal to zero, that is not what I want. I'd like to a value in time that is equal to the product x*y. The variable x is a non linear function of time which represents a power, while y is the cumulative sum of the working hours of operation of the system, that goes from 0, if the system is not working, to 8760 if the system work every hour.</p>\n<pre class="lang-matlab prettyprint-override"><code>clear all\nclose all\nclc\n\n\naddpath('C:\\gurobi1103\\win64\\examples\\matlab')\n\n%% Input data\n\n% Define the main path manually, e.g. 'C:\\Users\\My_models'\n path_main = 'C:\\Users\\nanf\\Desktop\\H2-districts';\n% path for input files\n path_input = fullfile(path_main, 'Input');\n% Define the path for functions\n path_functions = fullfile(path_main, 'Functions');\n\n% Reading an Excel file from the Input directory\n excelFilePath1 = fullfile(path_input, 'Inputs_BoundaryLoads_2022.xlsx');\n excelFilePath2 = fullfile(path_input, 'nestel_demand.csv');\n excelFilePath3 = fullfile(path_input, 'PriceImpExp_ele.xlsx');\n Input1 = readtable(excelFilePath1);\n Input2 = readtable(excelFilePath2);\n Input3 = readtable(excelFilePath3);\n%% Pre-processing\n nHours = 8760; % Number of hours simulated [8760h]\n irradiance = Input1.G; % Hourly solar irradiance [W/m^2]\n idxHr2ToEnd = (2:nHours)'; % Hours until the end\n Time = (1:nHours)'; % Time vector\n days = nHours/24; % Number of days simulated\n weeks = days/7; % Number of weeks simulated\n clear t; \n linew = 1.5; \n font = 18;\n \n%% INPUT PARAMETERS\n\n % general inputs\n\n bigM = 1e8; % Large number for big-M constraints\n MaxSimTime = 900; % Maximum time for MILP solver [s] \n deltat = 3600; % time step di 1h [s] \n\n % Electrical district demand\n \n P_load = Input2.P_el_nest_h; % NEST electrical demand [kW]\n\n % Fixed technical parameters \n\n HHV = 39.39 * 3.6 * 10^3; % Hydrogen higher heating value [kJ/kg] \n \n % Costs and Efficencies \n\n c_h2 = 2; % cost of hydrogen [CHF/kg]\n c_gridimp = Input3.Priceimpgreen; % [CHF/kWh]\n c_gridexp = Input3.PriceexpPV; % [CHF/kWh]\n eff_b = 0.95; % constant efficiency of the battery (round trip efficency)\n eff_PV = 0.17; % constant efficiency of the PV system\n eff_FC = 0.50; % Nominal electrical efficency of FC \n\n % Lifetime in hours for PEMFC from Technology RoadMap-Hyydrogen and Fuel Cells,IEA(2015) \n nH_lifetime = 40000; % [h]\n % PEM fuel cell lifetime was defined by the time elapsed until 10% of the initial voltage/performance is lost\n Delta_eff_FC = 0.1*eff_FC; % [-]\n % Fuel Cell degradation rate as a constant value in Nani-Model\n Const1 = Delta_eff_FC/nH_lifetime; % [1/h]\n % further constant for MILP model from Taylor expansion\n Const3 = Const1/HHV/eff_FC^2; %[kg/h/kJ]\n % Const2 = Const3*P_FC_opt;\n\n % Fuel Cell (FC)\n S_FC_min = 0; % Minimum size FC [kW]\n S_FC_max = 60; % Maximum size FC [kW]\n\n % PV \n P_PV_peak_ref = 100; % Reference value peak power PV [kW]\n Area_PV_ref = P_PV_peak_ref/eff_PV; % Reference area PV [m2]\n Area_PV_min = 0; % Minimum area PV [m2]\n Area_PV_max = Area_PV_ref*2; % Maximum area PV [m2]\n \n % Battery\n \n C_b_max = 96 * 3.6 * 10^3; % Battery capacity [kJ]\n C_b_min = C_b_max / 3; % MIN Battery capacity [kJ]\n P_b_max = C_b_max / 3600; % Battery capacity (1C rate) [kWh]\n \n % unit prices and lifetime components\n\n d = 0.05;%0.04; % Discount rate\n ann = d / (1 - (1 + d)^(-20)); % annuity factor calculated with plant lifetime \n \n UP_PV = 1300;%1240; % Unit price PV [CHF/kW_p]\n life_PV = 25;%30; % Lifetime PV [years]\n maint_PV = 0.01;%0.0158; % Annual cost maintenance PV, frac total cost\n ann_PV = d / (1 - (1 + d)^(-life_PV));\n \n UP_b = 1000;%600 % Unit price battery [CHF/kWh]\n life_b = 12;%10; % Lifetime battery [years]\n maint_b = 0.02; % frac capex \n ann_b = d / (1 - (1 + d)^(-life_b));\n \n UP_FC = 950;%3000 % Unit price FC [CHF/kW]\n life_FC = 7.5;%15 % Lifetime FC [years]\n maint_FC = 0.024;%0.02 % Annual cost maintenance FC, frac capex cost\n ann_FC = d / (1 - (1 + d)^(-life_FC));\n \n aux_maxs = (S_FC_max+nHours); \n aux_mins = 0; \n\n aux_maxd = S_FC_max; \n aux_mind = -nHours; \n\n\n%% PWL \n run PWL_productcontvariables.m\n%% Define the optimization problem and the optimization variables\n\nsizingprob = optimproblem;\n\n%% DECISION VARIABLES\n\n% SIZING decision variables\n\n % Battery capacity in [kJ]\n C_b = optimvar('C_b','LowerBound',C_b_min,'UpperBound',C_b_max); % C_b actual installed capacity,C_b_max= max capacity we can have\n % Fuel Cell size in [kW]\n S_FC = optimvar('S_FC','LowerBound',S_FC_min,'UpperBound',S_FC_max);\n % PV area in [m2]\n Area_PV = optimvar('Area_PV','LowerBound',Area_PV_min,'UpperBound',Area_PV_max);\n\n% OPERATIONAL decision variables\n \n % fuel cell generated power in [kW]\n P_FC = optimvar('P_FC',nHours,'LowerBound',0,'UpperBound',S_FC_max);\n % additional variables for FC operation implementation\n P_FC_On = optimvar('P_FC_On',nHours,'LowerBound',0,'UpperBound',S_FC_max);\n delta_On = optimvar('FC_On',nHours,'Type','integer','LowerBound',0,'UpperBound',1);\n % Degradation auxiliary variable [h]\n w_hours = optimvar('w_hours',nHours,'LowerBound',0,'UpperBound',nHours); %cumulative summation of FC_On\n % mass flow rate of H2 [kg/h]\n m_flow_H2 = optimvar('m_flow_H2',nHours,'LowerBound',0,'UpperBound',S_FC_max/eff_FC/HHV.*3600*3);\n \n % imported power from the grid in [kW]\n P_imp = optimvar('P_imp',nHours,'LowerBound',0);\n % exported power to the grid in [kW]\n P_exp = optimvar('P_exp',nHours,'LowerBound',0);\n % Battery energy content in [kWh]\n E_b = optimvar('E_b',nHours,'LowerBound',0,'UpperBound',C_b_max); \n % Battery charging power in [kW]\n P_b_ch = optimvar('P_b_ch',nHours,'LowerBound',0,'UpperBound',P_b_max);\n % Battery discharging power in [kW]\n P_b_disch = optimvar('P_b_disch',nHours,'LowerBound',0,'UpperBound',P_b_max);\n\n %% Additional Decision Variables for PWA Approximation\n\n % Squared variables for X and Y\n square_X = optimvar('square_X', nHours,'LowerBound', 0,'UpperBound',(nHours+S_FC_max)^2*2); % f(t)=x^2, x=(P_fc+w_hours)^2\n square_Y = optimvar('square_Y', nHours, 'LowerBound', 0, 'UpperBound',(nHours+S_FC_max)^2*2); % f(t)=y^2, y=(P_fc-w_hours)^2\n X_var = optimvar ('X_var',nHours, 'LowerBound',aux_mins,'UpperBound',aux_maxs);\n Y_var = optimvar ('Y_var',nHours,'LowerBound',aux_mind,'UpperBound',aux_maxd);\n\n delta_sum1 = optimvar('delta_sum1','Type','integer','LowerBound',0,'UpperBound',1);\n delta_sum2 = optimvar('delta_sum2','Type','integer','LowerBound',0,'UpperBound',1);\n delta_sum3 = optimvar('delta_sum3','Type','integer','LowerBound',0,'UpperBound',1);\n delta_sum4 = optimvar('delta_sum4','Type','integer','LowerBound',0,'UpperBound',1);\n \n aux_sum1 = optimvar('aux_sum1','LowerBound',aux_mins,'UpperBound',aux_maxs);\n aux_sum2 = optimvar('aux_sum2','LowerBound',aux_mins,'UpperBound',aux_maxs);\n aux_sum3 = optimvar('aux_sum3','LowerBound',aux_mins,'UpperBound',aux_maxs);\n aux_sum4 = optimvar('aux_sum4','LowerBound',aux_mins,'UpperBound',aux_maxs);\n\n delta_diff1 = optimvar('delta_diff1','Type','integer','LowerBound',0,'UpperBound',1);\n delta_diff2 = optimvar('delta_diff2','Type','integer','LowerBound',0,'UpperBound',1);\n delta_diff3 = optimvar('delta_diff3','Type','integer','LowerBound',0,'UpperBound',1);\n delta_diff4 = optimvar('delta_diff4','Type','integer','LowerBound',0,'UpperBound',1);\n\n aux_diff1 = optimvar('aux_diff1','LowerBound',aux_mind,'UpperBound',aux_maxd);\n aux_diff2 = optimvar('aux_diff2','LowerBound',aux_mind,'UpperBound',aux_maxd);\n aux_diff3 = optimvar('aux_diff3','LowerBound',aux_mind,'UpperBound',aux_maxd);\n aux_diff4 = optimvar('aux_diff4','LowerBound',aux_mind,'UpperBound',aux_maxd);\n \n % Reformulated product term\n PFC_w_hours = optimvar('PFC_w_hours', nHours, 'LowerBound', 0, 'UpperBound', S_FC_max*nHours);\n\n %% Derived variables\n\n % PV generated power\n P_PV = irradiance.*eff_PV*Area_PV/1000; % [kW]\n P_PV_peak = 1000*eff_PV*Area_PV/1000; % [kW]\n \n % C-rate of battery [kWh]\n P_b_lim = C_b / 3600; % new max capacity in [kWh]\n \n %% CONSTRAINTS\n\n % energy balance\n\n sizingprob.Constraints.EnBalance = (P_FC + P_PV + P_b_disch + P_imp) == (P_b_ch + P_load + P_exp);\n \n % BATTERY\n\n % sizingprob.Constraints.NoSimultaneousChDisch = discharging_on + charging_on &lt;= ones(nHours,1);\n sizingprob.Constraints.PowerBatt_ch_0 = P_b_ch(1) == 0; \n sizingprob.Constraints.PowerBatt_disch_0 = P_b_disch(1) == 0; \n\n %sizingprob.Constraints.Ch_on1 = P_b_ch &lt;= P_b_max * charging_on;\n sizingprob.Constraints.Ch_on2 = P_b_ch &lt;= P_b_lim;\n %sizingprob.Constraints.Disch_on1 = P_b_disch &lt;= P_b_max * discharging_on;\n sizingprob.Constraints.Disch_on2 = P_b_disch &lt;= P_b_lim;\n sizingprob.Constraints.E_b_update = E_b(idxHr2ToEnd) - E_b(idxHr2ToEnd-1) == P_b_ch(idxHr2ToEnd)*deltat - P_b_disch(idxHr2ToEnd)*deltat;\n sizingprob.Constraints.E_b_cont = E_b(1) == E_b(end); \n sizingprob.Constraints.E_b_max = E_b &lt;= C_b;\n % sizingprob.Constraints.E_b_min = E_b &gt;= 0.2 * C_b;\n \n % FC \n sizingprob.Constraints.MaxPowerFC = P_FC &lt;= P_FC_On;\n % sizingprob.Constraints.MinPowerFC = P_FC &gt;= 0.2 * P_FC_On;\n sizingprob.Constraints.PowerFC1 = P_FC_On &lt;= S_FC_max * delta_On;\n sizingprob.Constraints.PowerFC2 = P_FC_On &lt;= S_FC;\n sizingprob.Constraints.PowerFC3 = P_FC_On &gt;= S_FC - S_FC_max.*(ones(nHours,1) - delta_On);\n sizingprob.Constraints.PowerFC4 = P_FC &lt;= S_FC_max * delta_On;\n \n % Constraints for cumulative summation\n sizingprob.Constraints.SumCum_0 = w_hours(1) == delta_On(1);\n sizingprob.Constraints.SumCum_update = w_hours(idxHr2ToEnd) == w_hours(idxHr2ToEnd-1) + delta_On(idxHr2ToEnd);\n \n sizingprob.Constraints.pwl_segmentactsum = delta_sum1+delta_sum2+delta_sum3+delta_sum4==1 ;\n sizingprob.Constraints.pwl_segmentactdiff = delta_diff1+delta_diff2+delta_diff3+delta_diff4==1 ;\n\n%% (Pfc+whours)^2 \n% for auxiliary variable \n sizingprob.Constraints.auxsum11 = aux_sum1 &lt;= aux_maxs*delta_sum1;\n sizingprob.Constraints.auxsum12 = aux_sum1 &gt;= aux_mins*delta_sum1;\n sizingprob.Constraints.auxsum13 = aux_sum1 &lt;= X_var;\n sizingprob.Constraints.auxsum14 = aux_sum1 &gt;= X_var - aux_maxs *(1-delta_sum1);\n\n sizingprob.Constraints.auxsum21 = aux_sum2 &lt;= aux_maxs*delta_sum2;\n sizingprob.Constraints.auxsum22 = aux_sum2 &gt;= aux_mins*delta_sum2;\n sizingprob.Constraints.auxsum23 = aux_sum2 &lt;= X_var;\n sizingprob.Constraints.auxsum24 = aux_sum2 &gt;= X_var - aux_maxs *(1-delta_sum2);\n\n sizingprob.Constraints.auxsum31 = aux_sum3 &lt;= aux_maxs*delta_sum3;\n sizingprob.Constraints.auxsum32 = aux_sum3 &gt;= aux_mins*delta_sum3;\n sizingprob.Constraints.auxsum33 = aux_sum3 &lt;= X_var;\n sizingprob.Constraints.auxsum34 = aux_sum3 &gt;= X_var - aux_maxs *(1-delta_sum3);\n \n sizingprob.Constraints.auxsum41 = aux_sum4 &lt;= aux_maxs*delta_sum4;\n sizingprob.Constraints.auxsum42 = aux_sum4 &gt;= aux_mins*delta_sum4;\n sizingprob.Constraints.auxsum43 = aux_sum4 &lt;= X_var;\n sizingprob.Constraints.auxsum44 = aux_sum4 &gt;= X_var - aux_maxs *(1-delta_sum4);\n\n % sizingprob.Constraints.z_plus_lb_seg1 = X_var &gt;= xxs(1) * delta_sum1;\n sizingprob.Constraints.z_plus_ub_seg1 = X_var &lt;= xxs(2) * delta_sum1 + xxs(3) * delta_sum2 + xxs(4)*delta_sum3+xxs(5)*delta_sum4;\n % sizingprob.Constraints.z_plus_lb_seg2 = X_var &gt;= xxs(2) * delta_sum2;\n % sizingprob.Constraints.z_plus_ub_seg2 = X_var &lt;= xxs(3) * delta_sum2;\n % sizingprob.Constraints.z_plus_lb_seg3 = X_var &gt;= xx(3) * delta_sum3;\n % sizingprob.Constraints.z_plus_ub_seg3 = X_var &lt;= xx(4) * delta_sum3;\n % sizingprob.Constraints.z_plus_lb_seg4 = X_var &gt;= xx(4) * delta_sum4;\n % sizingprob.Constraints.z_plus_ub_seg4 = X_var &lt;= xx(5) * delta_sum4;\n \n sizingprob.Constraints.V_PWA_X = square_X == aas(1)* aux_sum1 + bbs(1) * delta_sum1 + aas(2) * aux_sum2 + bbs(2)* delta_sum2 +aas(3) * aux_sum3 + bbs(3)* delta_sum3 + aas(4) * aux_sum4 + bbs(4)* delta_sum4;\n\n%% DIFF\n% for auxiliary variable \n sizingprob.Constraints.auxdiff11 = aux_diff1 &lt;= aux_maxd*delta_diff1;\n sizingprob.Constraints.auxdiff12 = aux_diff1 &gt;= aux_mind*delta_diff1;\n sizingprob.Constraints.auxdiff13 = aux_diff1 &lt;= Y_var;\n sizingprob.Constraints.auxdiff14 = aux_diff1 &gt;= Y_var - aux_maxd *(1-delta_diff1);\n\n sizingprob.Constraints.auxdiff21 = aux_diff2 &lt;= aux_maxd*delta_diff2;\n sizingprob.Constraints.auxdiff22 = aux_diff2 &gt;= aux_mind*delta_diff2; \n sizingprob.Constraints.auxdiff23 = aux_diff2 &lt;= Y_var;\n sizingprob.Constraints.auxdiff24 = aux_diff2 &gt;= Y_var - aux_maxd *(1-delta_diff2);\n \n sizingprob.Constraints.auxdiff31 = aux_diff3 &lt;= aux_maxd*delta_diff3;\n sizingprob.Constraints.auxdiff32 = aux_diff3 &gt;= aux_mind*delta_diff3;\n sizingprob.Constraints.auxdiff33 = aux_diff3 &lt;= Y_var;\n sizingprob.Constraints.auxdiff34 = aux_diff3 &gt;= Y_var - aux_maxd *(1-delta_diff3);\n \n sizingprob.Constraints.auxdiff41 = aux_diff4 &lt;= aux_maxd*delta_diff4;\n sizingprob.Constraints.auxdiff42 = aux_diff4 &gt;= aux_mind*delta_diff4;\n sizingprob.Constraints.auxdiff43 = aux_diff4 &lt;= Y_var;\n sizingprob.Constraints.auxdiff44 = aux_diff4 &gt;= Y_var - aux_maxd *(1-delta_diff4);\n\n% sizingprob.Constraints.z_minus_lb_seg1 = Y_var &gt;= xxd(1) * delta_diff1;\nsizingprob.Constraints.z_minus_ub_seg1 = Y_var &lt;= xxd(2) * delta_diff1+xxd(3) * delta_diff2+xxd(4)*delta_diff3+xxd(5)*delta_diff4;\n% sizingprob.Constraints.z_minus_lb_seg2 = Y_var &gt;= xxd(2) * delta_diff2;\n% sizingprob.Constraints.z_minus_ub_seg2 = Y_var &lt;= xxd(3) * delta_diff2;\n% sizingprob.Constraints.z_minus_lb_seg3 = Y_var &gt;= xx(3) * delta_diff3;\n% sizingprob.Constraints.z_minus_ub_seg3 = Y_var &lt;= xx(4) * delta_diff3;\n% sizingprob.Constraints.z_minus_lb_seg4 = Y_var &gt;= xx(4) * delta_diff4;\n% sizingprob.Constraints.z_minus_ub_seg4 = Y_var &lt;= xx(5) * delta_diff4;\n\nsizingprob.Constraints.V_PWA_Y = square_Y == aad(1) * aux_diff1 + bbd(1) * delta_diff1 + aad(2) * aux_diff2 + bbd(2) * delta_diff2 + aad(3) * aux_diff3 + bbd(3) * delta_diff3 + aad(4) * aux_diff4 + bbd(4)* delta_diff4;\n\n% Reformulated product constraint using both PWA functions\nsizingprob.Constraints.ProductApprox1 = PFC_w_hours == (1/4) * (square_X - square_Y);\nsizingprob.Constraints.ProductApprox2 = PFC_w_hours &lt;=nHours*S_FC_max;\nsizingprob.Constraints.ProductApprox3 = PFC_w_hours &gt;=0;\n\n\n% mass flow rate calculation\nsizingprob.Constraints.massflowH2= m_flow_H2 == (P_FC./eff_FC./HHV).*3600 + PFC_w_hours*Const3*3600; % [kg/h]\n\n%% OBJECTIVE FUNCTION\n\ncost_inst = (P_PV_peak * UP_PV * ann_PV + S_FC * UP_FC * ann_FC + C_b/3600 * UP_b * ann_b)/1000; % [kEUR/y]\ncost_imp = sum(c_h2 * m_flow_H2) / 1000 + sum(P_imp .* c_gridimp) / 1000; % [kEUR/y]\ncost_exp = sum(P_exp .* c_gridexp) / 1000; % [kEUR/y]\ncost_maint = (maint_PV * P_PV_peak * UP_PV + maint_FC * S_FC * UP_FC + maint_b * UP_b * C_b/3600)/1000; % [kEUR/y]\n\ncost = cost_inst + cost_imp - cost_exp + cost_maint;\n\n% set objective \nsizingprob.Objective = cost;\n\n%% Solve optimization problem\n\nintcon = [];\n[solution,fval,reasonSolverStopped] = solve(sizingprob);\n</code></pre>\n"^^ . . . . . . . "0"^^ . . "2"^^ . "camera"^^ . . . . "So, what I understand from the comments is that those lines are not parallel."^^ . "0"^^ . . . . "1"^^ . . . . . . . . . . "rahnema1's comment from proving ground: "You may try GraphBLAS that contains masked matrix multiplication operators." Yes, "masked matrix multiplication" sounds like what this is. Thanks for the recommendation"^^ . "0"^^ . . . . "2"^^ . . . . "I asked ChatGPT, it told me "When you compile a Simulink model into a standalone executable (.exe) using Simulink Coder, the generated code is fixed at compilation time. The executable runs independently of MATLAB and does not support runtime parameter changes through MATLAB commands"\n\nDo you have other opinions or ideas to solve this problem? Thank you!"^^ . . "0"^^ . "matlab-figure"^^ . "h3"^^ . . . . "<p>Suspicions I had that cascade of actions internally to matlab are likely as follow:</p>\n<blockquote>\n<p>Mouse is moved &gt; HitTest cache is reset &gt; Event WindowMouseMotion is fired &gt; HitTest cache is updated &gt; WindowButtonMotionFcn callback is called</p>\n</blockquote>\n<p>seems to be true, so I came out with following solution (here using <code>UserData</code> to store user-defined callback if any + keeping debug messages, just for demo purpose):</p>\n<pre><code>function [] = TestFigEvents()\n%[\n ...\n\n % Attach as an event\n addlistener(fig, 'WindowMouseMotion', @onMouseMove); \n%]\nend\nfunction [] = onMouseMove(s, e)\n%[\n if (~iscell(s.UserData))\n\n disp('Begin &gt;&gt; Event');\n\n % Called by 'WindowMouseMotion' event\n % So just temporarely replace 'WindowButtonMotionFcn'\n s.UserData = { s.WindowButtonMotionFcn };\n s.WindowButtonMotionFcn = @onMouseMove;\n \n % Not clear why but does not work if not performing this 'drawnow'\n drawnow; \n\n disp('End &lt;&lt; Event');\n\n else\n\n disp('Begin &gt;&gt; Callback');\n\n % Called by 'WindowButtonMotionFcn' callback\n % So do my stuff now that 'hittest' is ok\n disp('Begin &gt;&gt; My own stuff');\n ht = hittest(s);\n disp(ht);\n disp('End &lt;&lt; My own stuff'); \n \n % Restore orginal 'WindowButtonMotionFcn' an call it if not empty\n s.WindowButtonMotionFcn = s.UserData{1};\n s.UserData = [];\n if (~isempty(s.WindowButtonMotionFcn)), \n disp('Begin &gt;&gt; User defined stuff');\n s.WindowButtonMotionFcn(s, e); \n disp('end &lt;&lt; User defined stuff');\n end\n\n disp('End &lt;&lt; Callback');\n\n end\n%]\nend\n</code></pre>\n<p>NB1: So far it is unclear why I need to call <code>drawnow</code> but without it is not working (adding <code>limitrate</code> option just decrease precision for <code>hittest</code> detection, and <code>nocallbacks</code> make it not to work).</p>\n<p>NB2: Just doing a <code>drawnow</code> in initial event-listener does not work:</p>\n<pre><code>function [] = onMouseMove(s, e)\n%[\n drawnow(); % This only does not make hittest to work\n ht = hittest(s);\n disp(ht);\n%]\nend\n</code></pre>\n<p>So I will go ahead with temporarely replacing <code>WindowButtonMotionFcn</code> callback if any <em>(+ quite strange but mandatory drawnow)</em>.</p>\n"^^ . . "0"^^ . . "Upon making that change, our answers were still giving different results! Unfortunately there is another bug I discovered in your `dist_point_plane` function. The final term in the numerator should be positive, so `...+d)/...`. Once this change was made, our answers are giving equivalent results."^^ . . . . "transformation"^^ . . . . . "Select an image ROI in Matlab app designer"^^ . . "As beaker said, this is just a display issue. The reason for that and ways to circumvent it are given in the linked duplicate."^^ . . "Is this a USB camera? If the camera does not advertise a grayscale format, then there is no way on earth to ask it to produce that. What is the camera make and model? We can check the USB descriptors to see what it actually offers."^^ . . "4"^^ . . . "0"^^ . . "5"^^ . . . "-1"^^ . . . . . "1"^^ . . "1"^^ . "0"^^ . . . . . . "<p>Add these lines after your existing code:</p>\n<pre><code>[x1Grid,x2Grid] = meshgrid(linspace(min(X(:,1)), max(X(:,1)), 100), ...\n linspace(min(X(:,2)), max(X(:,2)), 100));\n[~,scores] = predict(SVMModel, [x1Grid(:), x2Grid(:)]);\nscores = reshape(scores, [size(x1Grid,1), size(x1Grid,2), 3]);\n\n% add color to each region\n[pred,~] = predict(SVMModel, [x1Grid(:), x2Grid(:)]);\ncontourf(x1Grid, x2Grid, reshape(double(categorical(pred)), size(x1Grid)), 'LineStyle', 'none')\ncontourcmap('jet', 'Colorbar', 'on')\n\ncontour(x1Grid, x2Grid, scores(:,:,1) - max(scores(:,:,2:3),[],3), [0 0], 'k-');\ncontour(x1Grid, x2Grid, scores(:,:,2) - max(scores(:,:,[1 3]),[],3), [0 0], 'k--');\ncontour(x1Grid, x2Grid, scores(:,:,3) - max(scores(:,:,1:2),[],3), [0 0], 'k:');\n</code></pre>\n<p>The outcome is like:</p>\n<p><a href="https://i.sstatic.net/9QvNAmYK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9QvNAmYK.png" alt="enter image description here" /></a></p>\n<p><a href="https://i.sstatic.net/OFya2m18.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OFya2m18.png" alt="enter image description here" /></a></p>\n"^^ . . "<p>I tried the following:\nI have a MATLAB class <code>Value</code> and want to push it onto a java stack like so</p>\n<pre class="lang-matlab prettyprint-override"><code>stack = java.util.Stack\na= Value % constructor of MATLAB class \nstack.push({a})\n</code></pre>\n<p>Note that I have to wrap <code>a</code> because passing MATLAB objects to java methods is not supported.\nThen I try to regain:</p>\n<pre class="lang-matlab prettyprint-override"><code>a1 = stack.pop\n</code></pre>\n<p>But here, <code>a1</code> turns out to be array of type <code>java.lang.Object[]</code> but it is empty:</p>\n<pre class="lang-none prettyprint-override"><code>a1 = \n\n java.lang.Object[]\n\n [[]]\n</code></pre>\n<p>Can anyone tell me what went on and how to get what I want.\nTo be honest, I will now just use matlab arrays to emulate the stack, but still...\nI am curious.</p>\n"^^ . . . . . "0"^^ . "0"^^ . "windows"^^ . . . "-2"^^ . "<p><strong>Problem:</strong> Use MATLAB's symbolic toolbox to find the general and particular solution for the transient response of i(t) in a simple/canonical RLC circuit.</p>\n<p><strong>Challenge:</strong> Execution of the line <code>iSol(t) = dsolve(eqn, [cond1, cond2]);</code> in the code below raises an error that states that the solver is unable to reduce the square system because the number of equations differes from the number of indeterminates. Can someone help me resolve this issue?</p>\n<h2>Code</h2>\n<pre><code>syms i(t) R L C V0 \n\n% Define component values\nR = 10;\nL = 1;\nC = 1;\nV0 = 12;\n\n% Define the differential equation\neqn = L*diff(i(t), t, 2) + R*diff(i(t), t) + (1/C)*i(t) == 0;\n\n% Define initial conditions\ncond1 = i(0) == 0; % i(0) = 0\ncond2 = diff(i(t),t) == V0/L; % di/dt(0) = V0/L\n\n% Solve the differential equation with initial conditions\niSol(t) = dsolve(eqn, [cond1, cond2]);\n\n% Display the particular solution\ndisp('Particular Solution for i(t):')\ndisp(iSol(t))\n</code></pre>\n"^^ . . . . . "0"^^ . . . . "Handle warning of "Array is wrong shape or size" when plotting a geopolyshape and setting the ColorData field in MATLAB"^^ . "word-cloud"^^ . "1"^^ . . "0"^^ . . . "0"^^ . "Why are my table columns not named properly?"^^ . "0"^^ . . "0"^^ . "0"^^ . "3"^^ . . "What is this function `PreProcess`, where did you get it from? What is the problem with the code? Do you get any error messages? Please copy-paste them in full into your post."^^ . . . . . "0"^^ . . . . . . . "@Irreducible How can I determine if my approach is correct based on the spectrum? I tried plotting the amplitude of the spectrum, but I don't know how to interpret the results."^^ . "0"^^ . "You're right! Sorry! https://itpp.sourceforge.net/4.3.1/"^^ . . "powershell"^^ . "1"^^ . . . "0"^^ . . . . "1"^^ . "Doesn't the last line of the table clearly say "Matlab Object: Not Suppoorted"? What is "obviously untrue" about that? (And if it is supported ... how come you can't find the Matlab documentation that explains how it should be done?"^^ . . . "0"^^ . . "0"^^ . "The camera is USB 640x480 and produces YUYV with the Y component holding the upper 8 bits and U / V components holding the lower 6 bits of a 14bit gray scale pixel. I am using windows for Matlab. The product I am working on is actually linux where I can use gstreamer to get the "YUYV" data and then have a custom plugin to convert to 14 or 8 gray. The camera is the problem it is incorrectly saying YUYV when it is not. I can do the conversion if I have the raw data."^^ . . . "0"^^ . . . "<p>I have two bodies in space composed by 3 points.</p>\n<pre><code>A = [-50.0098 -181.0869 -37.5881];\nB = [ -49.8410 -180.8097 -41.1383];\nC = [-49.5887 -180.3952 -46.4462];\n\nA = [-50.199 -180.93 -37.249];\nB = [-50.256 -180.823 -33.686];\nC = [-50.341 -180.657 -28.359];\n</code></pre>\n<p>I want to plot a plane through one of the 3D points and calculate the distance between the other point and this plane.</p>\n<p>Additionally, I want to plot it.</p>\n<p>I used the following function:</p>\n<pre><code>%% ====== FUNCTION ======\nfunction [normal, d, X, Y, Z] = plot_line_deviazione(p1, p2, p3, x_min, x_max, y_min, y_max)\n% This function plots a line from three points. \n% I/P arguments: \n% p1, p2, p3 eg, p1 = [x y z]\n% \n%\n% O/P is: \n% normal: it contains a,b,c coeff , normal = [a b c]\n% d : coeff\nnormal = cross(p1 - p2, p1 - p3);\nd = p1(1)*normal(1) + p1(2)*normal(2) + p1(3)*normal(3);\nd = -d;\nx = x_min:x_max; y = y_min:y_max;\n[X,Y] = meshgrid(x,y);\nZ = (-d - (normal(1)*X) - (normal(2)*Y))/normal(3);\nmesh(X,Y,Z)\n</code></pre>\n<p>In the following way:</p>\n<pre><code> figure\nplot3(A(:,1),A(:,2),A(:,3),'r.','Markersize',25)\nhold on\nplot3(B(:,1),B(:,2),B(:,3),'r.','Markersize',25)\nplot3(C(:,1),C(:,2),C(:,3),'r.','Markersize',25)\n[normal0, d0, X0, Y0, Z0] = plot_line_deviazione(A, B, C, -100, 100, -100, 100); % new plane\n\ndot(X-d0,normal0)\n</code></pre>\n<p>The &quot;dot&quot; would be the distance that I was looking for. Is this correct? How can I plo it?</p>\n<p>Thanks!</p>\n"^^ . . . . "0"^^ . "It would be interesting to know what you're trying to achieve with this, you could set variables to specific values when entering different scripts to trace whether you're in the second script, or at least make the sub mlx into a function file instead of using layered scripts, since this is typically more robust regardless whether those are "live" or "traditional" scripts"^^ . . "0"^^ . . . . . "Thanks for the reply! It's worked perfect! How about adding color to each region in above figure? Can we do that too? Thanks in advance!"^^ . "How can installed the preprocess library on matlab toolbox?"^^ . . "@jdweng stl is a file extension and is irrelevant to the tag [tag:stl]. Can you read the tag description one more time?"^^ . . "<p>How do I hide the tick marks, but keep the tick labels on both y axis of a graph?</p>\n<p>My formatting for the axis is</p>\n<pre><code>yyaxis left;\nb = bar(data(2:end-1,:)', &quot;stacked&quot;);\nxticklabels(data(1, :));\nax1 = gca;\nax1.YGrid = &quot;on&quot;;\nax1.YLim = [0, 1000];\n...\n\nyyaxis right;\nl = plot(data(end, :), 'k');\nl.LineWidth = 2;\nax2 = gca;\nax2.YLim = [0,30];\n\nbox off;\n</code></pre>\n<p>The result:</p>\n<p><a href="https://i.sstatic.net/2fl8TCFM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2fl8TCFM.png" alt="Current Image" /></a></p>\n<p>The desired format:</p>\n<p><a href="https://i.sstatic.net/jy072yfF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jy072yfF.png" alt="" /></a></p>\n"^^ . . "symmetric"^^ . . "0"^^ . . "mixed-integer-programming"^^ . "0"^^ . . . . . "chtz, pt 2: Essentially for that small binary matrix "L_block", each row of L_blockcorresponded to some submatrix of all 1s in C = ( A * B ) .* L. In the visual example I provided, L_block has 9 rows, thus there are 9 submatrices ("blocks") of 1s in L, each having their own row and column indices in L (and thus C), and I went over each of these submatrices (per each row in L_block) to evaluate that submatrix's entries in C."^^ . . . . "<p>I am working with fluorescence microscopy images of blood vessels in the brain, stored as HDF5 files (<code>.h5</code>). My goal is to extract vessel dimensions (diameters) from each frame in a time series and analyze how they change over time.</p>\n<p>Currently, I am using MATLAB to:</p>\n<ol>\n<li>Load the <code>.h5</code> file and extract individual frames.</li>\n<li>Apply Gaussian filtering and contrast enhancement to improve vessel visibility.</li>\n<li>Perform edge detection (Canny) and skeletonization to extract vessel centerlines.</li>\n<li>Compute vessel diameters using the Euclidean distance transform from the skeleton.</li>\n</ol>\n<p>However, I am running into several issues:</p>\n<ul>\n<li>Edge detection is inconsistent and picks up artifacts inside the vessel.</li>\n<li>The skeleton sometimes extends beyond the vessels or is not continuous.</li>\n<li>Extracted diameters appear constant, even when the vessel visibly changes size.</li>\n</ul>\n<p><a href="https://i.sstatic.net/YLupyix7.jpg" rel="nofollow noreferrer">Working example of an h5 frame</a></p>\n<h3>Current Approach in MATLAB</h3>\n<p>Here’s the code I am using to manually select vessels and compute diameters:</p>\n<pre class="lang-matlab prettyprint-override"><code>% Load a single frame from HDF5 file\nframe = double(h5read('file.h5', '/recording', [1,1,1,1000], [512,512,1,1]));\n\n% Preprocessing: Smoothing &amp; contrast enhancement\nframe = imgaussfilt(frame, 2);\nframe = imadjust(mat2gray(frame), stretchlim(mat2gray(frame), [0.01, 0.99]));\n\n% Edge detection &amp; binarization\nbw = imbinarize(frame, 'adaptive', 'Sensitivity', 0.5);\nbw = bwareaopen(bw, 50);\n\n% Skeletonization &amp; distance transform\nskeleton = bwskel(bw);\ndistance_map = bwdist(~bw);\ndiameter_map = distance_map * 2;\n\n% Extract diameters along the skeleton\n[y, x] = find(skeleton);\ndiameters = arrayfun(@(i) diameter_map(y(i), x(i)), 1:length(x));\n\n% Plot results\nfigure;\nimshow(frame, []); hold on;\nscatter(x, y, 15, diameters, 'filled'); % Color vessels by width\ncolormap(jet); colorbar;\ntitle('Vessel Skeleton &amp; Diameters');\n\n% Diameter profile plot\nfigure;\nplot(diameters, 'b.-');\nxlabel('Skeleton Point Index');\nylabel('Vessel Diameter (pixels)');\ntitle('Vessel Diameter Profile');\n</code></pre>\n<p><a href="https://i.sstatic.net/Cbt2b2fr.jpg" rel="nofollow noreferrer">Resulting edges and vessel diameter detection</a></p>\n<p>As you can see, the edges are picked up but not always, and the diameters are calculated on no real basis. They don’t seem to be particularly telling.</p>\n<h3>Question:</h3>\n<ol>\n<li>How can I ensure accurate edge detection that captures the actual vessel boundaries and calculate their diameters?</li>\n</ol>\n"^^ . . "0"^^ . . . . . . "1"^^ . . "The `WinMain` message is kind of bogus. Mingw looks for *either* `main` or `WinMain`, but only includes the latter in the message when none of them is found."^^ . . "1"^^ . . . . . . . "This extencion does not work great, every time I run a cell, it opens a new instance of matlab terminal. Maybe there are some problems with my settings"^^ . . "Also, you don’t need to loop in MATLAB: `R = image(:,:,1);`."^^ . "0"^^ . "need to vectorize efficiently calculating only certain values in the matrix multiplication A * B, using a logical array L the size of A * B"^^ . . . . "0"^^ . . . . . "Unrelated to the question, but you should use a perceptually uniform colormap. With the one you are using, a change from 0.1 to 0.2 is almost imperceptible, whereas from 0.6 to 0.7 it is very prominent"^^ . . . . "0"^^ . "0"^^ . . . . . . . . . "@weirdgyn I don’t think you can. In Windows, when you make an icon in the start menu or the desktop to launch an application, you can set the startup folder. This is the working directory at startup, and so will be what `pwd` returns. You don’t know that the CTF is in the working directory. But what you *can* do is avoid needing that directory name. Most applications store user data in a fixed directory off of the home directory. Don’t write to the directory where the binary is. Constant data should be inside the CTF."^^ . . "preprocessor"^^ . "0"^^ . . "1"^^ . . "1"^^ . . "roi"^^ . "You could try combining the matrices into a cell; `S = {A,B,C,...,N};` then using `cat` again: `out = cat(3,{:});` but I doubt this would be much faster. As for doing operations - check out the page operations [here](https://blogs.mathworks.com/loren/2021/01/14/paged-matrix-functions/), [here](https://blogs.mathworks.com/matlab/2024/05/29/paged-matrix-functions-in-matlab-2024-edition/), and [here](https://au.mathworks.com/help/parallel-computing/distributed.pagefun.html)."^^ . . . . . . "reinforcement-learning"^^ . . "0"^^ . . "physics"^^ . . . . . "0"^^ . "1"^^ . . "0"^^ . "0"^^ . "<p>I drew two curves in a plot; permeability and impedance.\nAnd then tried to copy &amp; paste the same-type curves to compare 1:1.\nBut the curve in yyaxis right is linked to yyaxis left, and I don't know how to link it to yyaxis right.</p>\n<p>I tried to change the y axis of the copied/pasted curve from left to right.\nI'd like to see/compare two permeability curves in yyaxis left and two impedance curves in yyaxis right.</p>\n"^^ . . . "2"^^ . . . . "2"^^ . "1"^^ . . "0"^^ . . . "`diff(i(t),t) == V0/L` does not say that the derivative is that value at t=0. It makes the derivative constant. But I don’t know how to do this right, I have very little experience with this toolbox."^^ . . . . "If `L` is periodic, you could re-order `A` and `B` (thus implicitly also `L` and `C`) in a way that `C` has a block structure (and if necessary, afterwards re-re-order `C` to the desired order -- or better adapt the follow-up code to exploit the block-structure of `C`)."^^ . "As an aside: The `Set-ExecutionPolicy Bypass -Scope Process -Force;` statement is unnecessary, given that you're merely invoking a .NET method, not a script file."^^ . "1"^^ . . "0"^^ . . . . . . . . . "0"^^ . "<p>I am unable to get a transparent background in this MWE file; no errors. The procedure works fine for other types of Matlab plotting function</p>\n<pre><code> fileName = 'C-13.tex'; % Input file name\n text = ' this this this a is a test';\n text = lower(text);\n words = split(text);\n [uniqueWords, ~, idx] = unique(words);\n wordCounts = accumarray(idx, 1);\n wordTable = table(uniqueWords, wordCounts, 'VariableNames', {'Word', 'Frequency'});\n wordTable = sortrows(wordTable, 'Frequency', 'descend');\n topWordCount = 75; % Keep top 75 words\n wordTable = wordTable(1:min(topWordCount, height(wordTable)), :);\n hf = figure;\n wc = wordcloud(wordTable.Word, wordTable.Frequency);\n orangeColor = [1.0, 0.5, 0.0]; % Bright orange\n colorMap = repmat(orangeColor, numel(wc.WordData), 1);\n wc.Color = colorMap;\n %set(gca,'color', 'none');\n set(gcf, 'color', 'None');\n exportgraphics(hf,'out.pdf','BackgroundColor','none','ContentType','vector')\n</code></pre>\n"^^ . "medical-imaging"^^ . . . . . . "1"^^ . "0"^^ . . "I understand, set_param is not used ot call executable but rather interact with the model parameters. \n\nDid you use the simulink parameter as i indicated?\nIf so you cant pass a file, you need to pass a string with the parameter name and value as if it was a matlab command window command."^^ . . "0"^^ . . . . . . . "linearization"^^ . . "0"^^ . . . "2"^^ . . "0"^^ . "fft"^^ . "0"^^ . . "@Wolfie Would you mind turning your `repmat(1,1,...,n)` suggestion into an answer?"^^ . . . "0"^^ . . "1"^^ . . . . "mex"^^ . "image"^^ . . . . "matlab"^^ . "1"^^ . . "3"^^ . . . "2"^^ . "Please note that answers shouldn't be edited into the question. The correct way to deal with answers is to upvote those that helped you and accept the one that helped you most, see [What should I do when someone answers](/help/someone-answers). If you adapted rahnema1's answer so much, that it can be considered its own answer, please do add it as such. Link back to their original answer for attribution. [Answering your own question is allowed and even encouraged](/help/self-answer)."^^ . . "0"^^ . . "concatenation"^^ . . . . . "1"^^ . . . "-2"^^ . . "0"^^ . "Configuring the decoding software to generate a monochrome image should give you an 8 bit monochrome result. Ignoring the u and v components."^^ . . . . "`find(X==0,1)` compares the whole matrix to zero (maybe even producing a full matrix?), then looks for the first non-zero element. In the loop you don’t touch most of the matrix. And it being a sparse matrix, you likely have mostly zero elements (if not, don’t use a sparse matrix), so the loop should terminate really quickly. Note that `idx(n) = ii + (jj-1)*n` is the same as `idx(n) = kk`. And `x(ii,jj)==0` is the same as `x(kk)==0`. So removing the call to `ind2sub` should simplify and hopefully speed up your code."^^ . . . . "0"^^ . "If this a toy example or do you actually just want duplicates? If it's the later you can just use `repmat`. It's not clear to me what you mean by `MxNx...xn`, you want an n-dimensional array output? Because that's different to the 3-dimensional outputs in your examples."^^ . . . . "1"^^ . . "0"^^ . "1"^^ . . . . "0"^^ . . . "2"^^ . . "<p>I have a table that looks as follows:</p>\n<p><img src="https://i.sstatic.net/3GiuOVol.png" alt="wide table" /></p>\n<p>and I would like to get it into this format:</p>\n<p><img src="https://i.sstatic.net/Cb51SRer.png" alt="tall table" /></p>\n<p>in order to ultimately isolate all cells that have non-zero values:</p>\n<p><img src="https://i.sstatic.net/9ESo16KN.png" alt="filtered table" /></p>\n<p>I need to be able to identify row name and column name for each value in the resulting table.</p>\n<p>Somehow I am having trouble finding the most efficient way to do this in Matlab.</p>\n<p>This is a sample script preparing all the data up to the point to where I would do the unstacking.</p>\n<pre><code>row_names = {'row1','row2','row3'};\ncol_names = {'col1','col2','col3','col4','col5'};\ntable_values = [0.2, 0, 0, 0.3, 0;\n 0, 0.2, 0.2, 0, 0.1;\n 0.5, 0.5, 0, 0, 0];\n\ntable_source = array2table(table_values, 'RowNames', row_names, 'VariableNames', col_names);\nunstacked = unstack(table_source,col_names, col_names)\n</code></pre>\n<p>would be happy to receive any suggestions how to do this.\nThank you</p>\n"^^ . . . . . . . . . "You can't say "rounding doesn't work". Of course it does. However, there are different rounding policies. Matlab always rounds 0.5 up. Given your parameters, it is unlikely you are getting exactly 0.5. Have you manually converted the differing pixels to see where the differences happen? And, perhaps more important, why do you care? Why not just use the `rgb2gray` value?"^^ . "Luis' solution is the same as fireflies'. There are minor differences (in that Luis uses a sparse matrix and then makes sure to put the outputs in the correct place) but the actual computations are done exactly the same way...so I'm not sure why there is such a difference between those two solutions."^^ . . . . . . . "4"^^ . . "plot"^^ . "4"^^ . . "0"^^ . . . . . . . . "0"^^ . . . . . . . . . "1"^^ . "0"^^ . . . . . . . . "2"^^ . . "0"^^ . "0"^^ . . "2"^^ . "0"^^ . "Thanks Cris. What do you mean by 'looking through the data as stored'? You can of course use `find` to get the indexes of the non-zero elements -- but how would you then (quickly) find the first non-zero element? (without just looping through that list)"^^ . . "After rereading this, in addition to my comment above, how do you define "closest"? Is it (a form) of RMS? Your vector-scalar example appears to be wrong, as the largest *minimal* value would be picked, You'd need some form of `min(abs(S-a))`. Also note that you could use the second output of `min` rather than `find(A==min(A),1)`, as `[val, idx] = min(A)` gives you its index."^^ . "0"^^ . . . . . "0"^^ . . . "Do you get a warning in the MATLAB editor saying that the variable `a` appears to change size on every loop iteration? Also, why are you using `while` loops instead of, for example, `for y = 0:0.01:2*pi`?"^^ . "1"^^ . "How to read a CSV or Excel file of parameter names and values and assign them in MATLAB workspace"^^ . "matrix"^^ . . "0"^^ . "gurobi"^^ . . "anonymous-function"^^ . . . "2"^^ . "1"^^ . . "Oh, you could use `dot` instead of `sum(.*)`. Don’t know if it’s faster?"^^ . . "simulation"^^ . "0"^^ . "brackets"^^ . "0"^^ . "<p>I'm inputting a simple excel spreadsheet into Simulink to pull data from. I checked the data in Simulink via a Scope Block and it does not match the output of the Excel data when plotted. I've attached screenshots of both. It appears that Simulink is using previous values and copying over other values with that data instead. Any ideas for why this is occurring and/or how to fix it will be appreciated.[<a href="https://i.sstatic.net/fzknQsW6.png" rel="nofollow noreferrer">enter image description here</a>](<a href="https://i.sstatic.net/1w5CvH3L.png" rel="nofollow noreferrer">https://i.sstatic.net/1w5CvH3L.png</a>)</p>\n<p>I have tried adjusting the From Spreadsheet Block parameter inputs with no luck. I've checked the data in excel and it is okay. I've also reviewed the Simulink/Matlab page for the From Spreadsheet Block and can't find a reason for what is occurring.</p>\n"^^ . . . . "0"^^ . "2"^^ . "0"^^ . . "Show only tick labels and hide tick marks: MATLAB 2024b"^^ . . . "0"^^ . "0"^^ . "1"^^ . . . "simscape"^^ . "1"^^ . . . . . . "1"^^ . . . "Would be great if you could add a [mcve] of what you're working with already"^^ . "0"^^ . . . . . "0"^^ . . . "0"^^ . . "You may want to have a look here: https://or.stackexchange.com/questions/180/how-to-linearize-the-product-of-two-continuous-variables"^^ . "<p>I am writing a C MEX S-Function to perform some calculations on various datastores. Therefore, I would like to access the datastore values directly from within the S-function without explicitly specifying them as input ports.</p>\n<p>I tried the function <code>mexGetVariablePtr</code>, but could not find a way to get the value of a datastore during simulation.</p>\n"^^ . . "signal-processing"^^ . "1"^^ . . . . . "scale"^^ . . . "0"^^ . "0"^^ . "xml"^^ . . "0"^^ . "0"^^ . "<p>I'm using the Holt-Winters model in MATLAB to forecast weather data. When I set the smoothing parameters (Alpha, Beta, and Gamma) too high, the model overfits the data and doesn't forecast well on new data.</p>\n<p>How can I adjust these parameters to avoid overfitting and improve the model's accuracy?</p>\n<p>I tried setting the smoothing parameters (Alpha, Beta, and Gamma) to higher values in my Holt-Winters model, expecting it to make the model more responsive to recent data. However, this caused the model to overfit the training data, leading to poor forecast accuracy when predicting new data. The model became too sensitive to past data, failing to generalize well to unseen data.</p>\n"^^ . "For the first question, it seems that I did not receive such warning. For the second question, I am more used to the `while` loop. It seems that this is not the key factor of the speed of the code."^^ . "sparse-matrix"^^ . . . "0"^^ . . . . "2"^^ . . . . . "0"^^ . . . . "0"^^ . . "s-function"^^ . "2"^^ . . . . "2"^^ . "https://en.cppreference.com/w/cpp/numeric/random"^^ . . . "<p>The comments on your question ask about whether you see a warning in your editor about the array size increasing every loop, since that's what makes those lines slow. This is what they're referring to:</p>\n<p><a href="https://i.sstatic.net/LhW3crZd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LhW3crZd.png" alt="warning" /></a></p>\n<p>You can work out up-front how big <code>a</code> is going to be and <a href="https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html" rel="nofollow noreferrer">pre-allocate</a> it. Using <code>for</code> loops makes this a bit clearer, so I've made both changes in the code below:</p>\n<pre><code>Maxdeviation= ComputeDeviationSum(0,0,0,mufT, mufD, mufC);\nMaximizingArg= [0,0,0];\n\n% Predefine sweep points\nX = 0:0.01:pi;\nY = 0:0.01:2*pi;\nZ = 0:0.01:2*pi;\ni=1;\n\n% Pre-allocate output since we know how big it's going to be\na = NaN(numel(X)*numel(Y)*numel(Z),4);\n\n% Loop over each point array\nfor ix = 1:numel(X)\n x = X(ix);\n for iy = 1:numel(Y)\n y = Y(iy);\n for iz = 1:numel(Z)\n z = Z(iz);\n\n deviation= x+y+z; % Just an example. The function is more complex.\n if deviation&gt; Maxdeviation\n MaximizingArg= [x, y,z];\n Maxdeviation= deviation;\n end\n\n % Assign output at this index to preallocated array\n a(i,:) = [x,y,z,deviation];\n i = i+1;\n end\n end\nend\n</code></pre>\n<p>Taking this further, it might be worth noting that storing <code>x,y,z</code> in the output array might be redundant, you could instead pre-allocate <code>a=NaN(numel(X),numel(Y),numel(Z))</code> and then store the function value as <code>a(ix,iy,iz)=deviation;</code>. Then you can easily index into the resulting array for given indices of <code>x</code>, <code>y</code> and <code>z</code>.</p>\n<p>Conversely if you don't want to use the indices <code>ix,iy,iz</code> for anything you could simplify the loops to be something like <code>for x = X</code> and remove the assignments <code>x = X(ix)</code></p>\n"^^ . . . . . . "winmain"^^ . "units-of-measurement"^^ . . . . "Please provide enough code so others can better understand or reproduce the problem."^^ . . . . . . "1"^^ . "0"^^ . "How to evaluate a MATLAB anonymous function that takes an arbitrary number of variables n, given a n-dimensional vector?"^^ . "2"^^ . "0"^^ . . "2"^^ . . . "0"^^ . . . "vectorization"^^ . . . "0"^^ . "0"^^ . . . "`repelem` now costs about 70% of time. I'll have a try on the parallel version of `repelem`. That's really nice and helpful"^^ . . . . . "<p>I'm relatively new to MATLAB so perhaps there's something I'm missing.\nThe task is the following: we must program a certain algorithm for optimizing a continuous function <code>f</code>: R<sup>n</sup> ---&gt; R. The thing is, to do so I need to minimize a scalar function that depends on <code>f</code>, and work with said minimum, for example:</p>\n<pre><code>%given f, and a vector y\n\ng=@(s) f(y + s*e_i) %e_i is the i-th canonical vector\n[lambda, ~]=fminsearch(g,0)\n\ndisp(lambda)\n</code></pre>\n<p>The problem is that, if for example f(x,y)=x+y, one can't input f([1,2]), you need to write f(1,2), so I don't know how to define the function <code>g</code> properly so I can find the needed scalar value.</p>\n<p>I know that if <code>f</code> were a fixed dimension, let's say 3, I could literally write</p>\n<pre><code>eval_f = @(v) f(v(1), v(2), v(3))\n\ng = @(s) eval_f(y + s*e_i)\n</code></pre>\n<p>but the code must be open to receive <em>any</em> function. I have also tried using <code>f(num2cell(y + s*e_i){:})</code> but I get an &quot;Invalid array indexing&quot; error, as I can't chain the parenthesis and an output.\nI have tried creating a more complex auxiliary function</p>\n<pre><code>eval_f=@(fun,v) fun(feval(@(x) x{:},num2cell(v)));\ng=@(s) eval_f(f,y + s*ei);\n</code></pre>\n<p>But doing <code>feval(@(x) x{:},v)</code> in the end only returns the first element of <code>v</code>, and <code>f</code> doesn't get evaluated correctly and thus <code>g</code> isn't correctly defined.</p>\n<p>How could I define g?</p>\n"^^ . "How to linearize the product of two continuous variables?"^^ . "How to calculate the phase response?"^^ . "0"^^ . "4"^^ . "<p>I have a matrix A and linearly independent vectors x_1,...,x_k, in the nullspace of A. I want to find x_{k+1}, ..., x_m such that x_1,...,x_k, x_{k+1}, ..., x_m is a basis of the null space of A.</p>\n<p>Is there a suitable Matlab command for this?</p>\n<p>Thank you</p>\n"^^ . "0"^^ . . "1"^^ . . "0"^^ . . "0"^^ . . . . "Error matlab : invalid dot name structure assignment because the structure array is empty"^^ . . . "Thank you. Only mistake that I did was not to use combination of curly and simple brackets. It works for me. Cheers"^^ . . . . "2"^^ . . . . . "<p>I want to do point cloud registration between two files.</p>\n<p>One file is in STL format and the other one is in XML format.</p>\n<p>I have transformed the STL file in a point cloud.</p>\n<p>How can I transform the XML into an STL file so I can get the second point cloud? It has x y z points.</p>\n<pre><code>reference_data = stlread('filename.stl');\nreference_points = reference_data.Points;\nptCloud = pointCloud(reference_points(:,:,:));\n</code></pre>\n"^^ . "custom-error-handling"^^ . . "0"^^ . . . . . "@Irreducible Yes, the results show that there is a linear shift in the phase spectrum and the magnitude is unchanged."^^ . "<p>I'm trying to create a custom block in Simscape that convert energy from pressurized water into a torque. Here is my code:</p>\n<pre><code>component pelton_turbine\n% Ce composant calcule le couple généré par l'eau sur la turbine.\n\n% Déclaration des ports\nnodes\n H = foundation.hydraulic.hydraulic; % Port hydraulique\n R = foundation.mechanical.rotational.rotational; % Port mécanique rotatif\nend\n\n% Déclaration des paramètres\nparameters\n eta = {0.85, '1'}; % Rendement de la turbine\n rho = {1000, 'kg/m^3'}; % Densité de l'eau\n r = {0.5, 'm'}; % Rayon moyen de la roue\n g = {9.81, 'm/s^2'}; % Gravité\nend\n\n% Déclaration des variables internes\nvariables\n Q = {0, 'm^3/s'};\n T = {0, 'N*m'}; % Couple généré\n H_head = {0, 'm'}; % Hauteur d'eau équivalente\nend\n\nbranches\n % Débit hydraulique pris directement depuis le port H\n Q : H.q -&gt; *;\nend\n\nequations\n\n % Calcul de la hauteur d'eau (pression convertie en mètre de colonne d'eau)\n H_head == H.p/ (rho * g);\n\n % Calcul du couple généré par l'eau\n T == {eta * rho * Q * r * sqrt(H_head * 2 * g), 'N*m'}; \n\n % Transmission du couple à l’axe mécanique\n R.t == T;\nend\n\nend\n</code></pre>\n<p>My problem is that I have this error when I try to build my component:</p>\n<pre><code>Invalid use of a value with unit cm^3*kg/(m*s^2) when attempting to bind a unit.\nThe value to which the unit is bound must not have an associated unit.\n • In pelton_turbine.pelton_turbine (line 36)\n eta = 0.8500\n rho = {1000, 'kg/m^3'}\n Q = {[1x1 double], 'cm^3/s'}\n r = {0.5000, 'm'}\n H_head = {[1x1 double], 'm'}\n g = {9.8100, 'm/s^2'}\n</code></pre>\n<p>I don't get why the flow rate (Q) is in cm^3/s instead of m^3/s and I don't know how to change it. Do you have an idea ?</p>\n<p>Since Q is a through variable I can't define his unit. I also tried changing the units in the Configuration Parameters in my .slx file (I changed cm^3/s into m^3/s for the flow rate) but it didn't have any effect on my .ssc file and I keep getting the error.</p>\n"^^ . . . . "That function is not part of MATLAB. Anyway, this is not an issue with the matrix multiplication, because that cannot change. You are giving different matrices to the multiplication. Run the code step by step in each version of MATLAB (this is what the debugger is for, learn to use it!), and compare each of the intermediate values, until you see a difference. You just need to compare matrix sizes, because the error indicates you get a different size for at least one of the two operands. Once you know where the program starts to diverge, you know where to start looking for the problem."^^ . "java"^^ . . . "2"^^ . . . . . . . . . . . "0"^^ . . "1"^^ . . . "<p>I'm trying to simulate a satellite tracker. With ode45 I have de state of the satellite for each time and then convert position to Azimuth-Elevation local coordinates. If the object enters in the field of view (expressed as a mask of Az-El), the integration stops and changes the step to a smaller one in order to obtain more points inside. I'm trying to use an 'Events' function, which compares de Az-El of the satellite with the radar's mask. <strong>The problem is ode45 detects an event when it's not supposed to, and vice versa.</strong></p>\n<p>I discarded the transformation to angular coordinates as the origin of the problem, and i tried to reduce the step size.<a href="https://i.sstatic.net/E1cJ5gZP.png" rel="nofollow noreferrer">Az-El plot</a></p>\n<pre><code>load(&quot;maskmin.mat&quot;)\nload(&quot;maskmax.mat&quot;)\nAzmaskmin = maskmin(:,1);\nElmaskmin = maskmin(:,2);\nAzmaskmax = maskmax(:,1);\nElmaskmax = maskmax(:,2);\nt_total = []; y_total = [];\naz_total = []; el_total = [];\nt_actual = t0; y_actual = y0;\noptions = odeset('RelTol',3e-14,'AbsTol',3e-14,'Refine',10,'NormControl','on',...\n 'Events', @(t,y) eventos_radar(t, y, lat_radar,...\n lon_radar, alt_radar,Azmaskmin,Azmaskmax,Elmaskmax,Elmaskmin));\naze = [];\nele = [];\nyee = [];\ntee = [];\n% Principal loop\nr1 = 100; % Big step\nrt = 10; % Small step\ndt = r1; % Initial condition isn't inside FOV\nwhile t_actual &lt; tf - dt\n [t, y, te, ye] = ode45(@(t,y)ecuacion_movimiento(t, y, mu),...\n [t_actual:dt:tf], y_actual, options);\n t_total = [t_total; t];\n y_total = [y_total; y];\n % Update next integration\n t_actual = t(end);\n y_actual = y(end,:)';\n % Event check\n if ~isempty(ie)\n if dt == r1\n dt = rt;\n fprintf('Entrance in t = %.2f segundos\\n', t_actual);\n elseif dt == rt\n dt = r1;\n fprintf('Exit in t = %.2f segundos\\n', t_actual);\n end\n t_actual = te(end);\n y_actual = ye(end, :)';\n end\nend\n% Procesing results\nprocesar_resultados(t_total, y_total, lat_radar, lon_radar, alt_radar,...\n Azmaskmin,Azmaskmax,Elmaskmax,Elmaskmin);\nfunction [value, isterminal, direction] = eventos_radar(t, y, lat_radar,...\n lon_radar, alt_radar,Azmaskmin,Azmaskmax,Elmaskmax,Elmaskmin)\n[az, el] = calcular_az_el(y(1:3)', lat_radar, lon_radar, alt_radar, t);\nif az&gt;=Azmaskmax(1) &amp;&amp; az&lt;=Azmaskmax(end)\n el_min = interp1(Azmaskmin, Elmaskmin, az);\n el_max = interp1(Azmaskmax, Elmaskmax, az);\n value = [el_max - el, el - el_min];\n isterminal = [1 1]; % Detect changes of sign\nelse\n value = [Elmaskmax(1) - el, el - Elmaskmax(1)];\n % Elmaskmax(1) is the El value from the FOV corner in order to get continuous values of 'value' when the object is % outside\n isterminal = [0 0]; % Ignores changes of sign\nend\ndirection = [0 0];\n</code></pre>\n<p><a href="https://i.sstatic.net/cwbt6Zcg.png" rel="nofollow noreferrer">'Value'-time</a>: The left plot is using the y_total values once the simulation stops, and the rigth plot is using the values of the y that the event function receives from the ode 45.</p>\n<p>Anyone knows what is going on? Any help is welcome!!</p>\n"^^ . . . . "1"^^ . "I think this is the answer: https://stackoverflow.com/questions/24647269. Note that passing Matlab objects to Java is **not supported** by Matlab. That is clear from the documentation."^^ . "0"^^ . . "2"^^ . . . . "0"^^ . . "0"^^ . . . "How do I change a measurment unit in a Simscape custom block?"^^ . . . . . "Out of range values when reading a MATLAB file with R.matlab"^^ . . . "<p>I have been trying to linearize a simple PLL model using the mixed signal blockset, and I can't manage to do it. What I don't understand, is that the block &quot;Integer N Single Modulus&quot; has the exact same blocks and you are able to plot a bode with it. However, when I try to place the block myself with the same configuration I get the following error when trying to linearise and plot the Bode:</p>\n<pre class="lang-none prettyprint-override"><code>'pll_filtre/Loop Filter3/Convert Sample Time' implements a Jacobian method, but failed to configure its Jacobian dimensions in the DoPostPropagationTasks function.\n</code></pre>\n<p>Here is the PLL:\n<img src="https://i.sstatic.net/YT8tEix7.png" alt="PLL using mixed-signal blockset" /></p>\n<p>I have tried to change the block &quot;Loop Filter&quot; for a Transfer Function of a second order loop filter, but I only got the following error:</p>\n<pre class="lang-none prettyprint-override"><code>Error:Propagation delay input to pll_filtre/VCO/Variable Pulse Delay is negative. To obtain a causal simulation, the propagation delay must be positive.\n</code></pre>\n<p>Here is the configuration of this test:\n<img src="https://i.sstatic.net/67RmU0BM.png" alt="PLL with transfer function" /></p>\n<p>I cannot find any of those errors online.</p>\n<p>How to linearize this simple PLL as it's done in the pre-made block?</p>\n"^^ . . "0"^^ . . . ".net-assembly"^^ . . "filter"^^ . "0"^^ . . "1"^^ . . . . . . . . "1"^^ . . "0"^^ . "validation"^^ . "1"^^ . . . . . . "0"^^ . . . . . . . "IT++ is a C++ library of mathematical, signal processing and communication classes and functions. Its main use is in simulation of communication systems and for performing research in the area of communications. The kernel of the library consists of generic vector and matrix classes, and a set of accompanying routines. Such a kernel makes IT++ similar to MATLAB, GNU Octave or SciPy."^^ . . . . . . "1"^^ . . . . "neural-network"^^ . . "<p>How can I get the same random results in <a href="https://itpp.sourceforge.net/4.3.1/" rel="nofollow noreferrer">IT++</a> and Matlab?\nFor example, the default random generator algorithm in Matlab is &quot;twister&quot; which is &quot;Mersenne Twister&quot; with the keyword <code>mt19937ar</code>.\nSo, when I write <code>rng(0, &quot;twister&quot;)</code> in Matlab, the results are always the same (seed=0.)\nBut, I don't know how to set it in IT++ to get to the same random results between Matlab and IT++.\nFor testing, we can compare the <code>rand(1,5)</code> and <code>randu(5)</code> in Matlab and IT++, respectively.</p>\n"^^ . . . . . "2"^^ . . "If `A` is size `MxN` and `S` is size `MxNxZ` then `A-S` should work with implicit expansion since release R2016b to give you something the same size as `S`. If you're using an older version of MATLAB you'd need to use `bsxfun( @minus, S, A )`. Then you might need a different metric than `abs` to find the closest "slice" of the matrix, how are you defining that for a 2D matrix?"^^ . "0"^^ . . "0"^^ . . . . . "0"^^ . . . . . . "How to do A* Algorithm in Path Planing with Simulink ( Drone Navigation System )"^^ . . . "<p>MATLAB is throwing a warning and not plotting a <code>geopolyshape</code> when setting the <code>ColorData</code> field; however the shape is plotted when <code>ColorData</code> isn't set. The example code below demonstrates the issue. I am using MATLAB2024b.</p>\n<p>Note the latitude and longitude correspond to a H3 resolution 8 hexagon. I don't think the issue is because it's an H3 cell because other H3 cells plot fine with <code>ColorData</code> but I'm sharing for completeness.</p>\n<p>So how can I plot this <code>geopolyshape</code> while setting <code>ColorData</code>?</p>\n<p><strong>MATLAB Warning:</strong></p>\n<pre><code>Warning: Error creating or updating TriangleStrip\n Error in value of property ColorData\n Array is wrong shape or size\n</code></pre>\n<p><strong>Example code</strong></p>\n<pre><code>lat = [41.9480823417544; ...\n 41.9232620388895; ...\n 41.9297343644414; ...\n 41.9610354203583; ...\n 41.9858827546380; ...\n 41.9794019931882; ...\n 41.9480823417544];\n\nlon = [-71.5797574810054; ...\n -71.5494225035612; ...\n -71.5033771429879; ...\n -71.4876121649763; ...\n -71.5179362450247; ...\n -71.5640362454369; ...\n -71.5797574810054];\n\n\n% Create geopolyshape\nshape = geopolyshape(lat, lon);\n\nfigure;\ntiledlayout('flow');\nnexttile;\ngeoplot(shape,'FaceColor','b');\ntitle('works')\n\nnexttile;\ngeoplot(shape,'FaceColor','flat');\ntitle('works')\n\nnexttile;\ngeoplot(shape,'FaceColor','flat','ColorData',1);\ntitle('fails and throws warning')\n\nnexttile;\ngeoplot(shape,'ColorData',5);\ntitle('fails and throws warning')\n</code></pre>\n<p><a href="https://i.sstatic.net/1KY0ygl3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1KY0ygl3.png" alt="MATLAB output" /></a></p>\n"^^ . "Convert histograms to values"^^ . "0"^^ . "2"^^ . "0"^^ . . "Oh boy... I really messed up. Sorry for bothering.\n\n1. Yes, I was still on Debug Mode *facepalm*. I thought I switched to Release, but I didn't.\n\n2. I simplified my minimal example to much. You are right with your reformulation but within my real algorithm this isn't working. When creating my example I was mor focussing on the operations rather than the numerical values.\n\nAnyway, problem is solved. Thanks!"^^ . "0"^^ . . . "The first problem is that the lines aren't parallel. The slope of the blue line is ~0.05442 while the slope of the red line is ~0.03997. But even if you make the slopes equal, given the precision of your points, you'll still probably have an error greater than 1e-5."^^ . . . . . "Nice analysis. For reference: The shortest, most efficient Eigen code is `M.noalias() = init * (r.array() + 1.).matrix();`, using a vector-vector outer product. `replicate` and any `rowwise()` operations are generally slow. But your guess is correct. The original code would be fast if OP hadn't forgotten to enable optimizations. Heck, even the [proper optimization mode for debugging , `-Og`](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html) would solve the performance issue and get less than 1 second runtime"^^ . . . "1"^^ . . . . . . . "3d"^^ . . . . . . "0"^^ . "0"^^ . . . . . . . . "0"^^ . . . . "1"^^ . . "<p>As you have discovered, MEX files are not currently supported on thread pools. However, MEX files <em>are</em> supported on process pools, i.e. try</p>\n<pre class="lang-matlab prettyprint-override"><code>parpool(&quot;Processes&quot;)\n</code></pre>\n"^^ . "0"^^ . "\n<ul>\n<li><p>Note that your installation method is likely incidental to your problem, given that both R and MATLAB seem to be working in principle.</p>\n</li>\n<li><p>I'm not familiar with MATLAB, but <a href="https://www.mathworks.com/help/matlab/ref/matlabwindows.html" rel="nofollow noreferrer">the docs</a> suggest that <strong>what you're likely looking for is the <code>-batch</code> parameter</strong> rather than <code>-r</code>, because only <code>-batch</code> &quot;Logs text to stdout and stderr.&quot;</p>\n<ul>\n<li>If I understand the docs correctly, <code>-batch</code> is meant for <em>non-interactive, CLI-only</em> calls that behave like a console (terminal) application (which is what you're looking for), whereas <code>-r</code> is meant for opening the MATLAB GUI and executing a startup command there, at the start of an <em>interactive</em> session.</li>\n</ul>\n</li>\n</ul>\n<p>Therefore, try the following:</p>\n<pre class="lang-bash prettyprint-override"><code># Run MATLAB script and capture output\n# Note the use of -batch instead of -r, which should also obviate the need for\n# -nodesktop and -nosplash\nmatlab_output &lt;- system(&quot;matlab -batch \\&quot;run('model.m'); exit;\\&quot;&quot;, intern = TRUE)\n</code></pre>\n"^^ . "1"^^ . . . . "Unable to find parallel lines- MATLAB code"^^ . . . . . "2"^^ . . . "<p>I have two chirp signals &quot;s1&quot; and &quot;s2&quot; in MATLAB:</p>\n<pre><code>% Parameter Setting\nR = 618e3; \nV = 7600; \nlambda = 0.0313; \nFa = 5000; % Sampling Rate (Can't not Change)\nN = 10000; % Sample Points\ntime_delay = 6.13e-5;\n\n% Axis Setting \nta = ( -N/2 : N/2-1 )/Fa;\nfa = ( -N/2 : N/2-1 )*( Fa/N );\n\ns1 = exp(-1j*2*pi/lambda*(V^2*(ta + time_delay).^2)/R);\ns2 = exp(-1j*2*pi/lambda*(V^2*(ta - time_delay).^2)/R);\n</code></pre>\n<p>It is obvious that <strong>s1</strong> has a positive shift (<em><strong>time_delay</strong></em>) on time axis <em><strong>ta</strong></em>, while the signal <strong>s2</strong> has a negative shift on time axis.</p>\n<p>I need to make the two signals equal, which means <strong>s1-s2</strong> equal to <strong>0</strong>.</p>\n<p>Besides, these two signals are aliasing due to the sampling rate <em><strong>Fa</strong></em> is not high enough.\nI am unable to change the sampling rate and the length of the time axis, as these are determined by certain radar parameters.</p>\n<p>I tried to use the time shifting property in the Fourier transform.</p>\n<pre><code>% Zero padding to avoid circular convolution\ns1 = [zeros(1,0.5*N), s1, zeros(1,0.5*N)];\ns2 = [zeros(1,0.5*N), s2, zeros(1,0.5*N)];\nfa2 = ( -N : N-1 )*( Fa/(2*N) ); % fa with padding (2N)\n\n% s1 Shifting By Fourier Property\nS1 = fftshift(fft(ifftshift(s1)));\nS1 = S1.*exp(-1j*2*pi.*fa2.*time_delay);\ns1r = fftshift(ifft(ifftshift(S1)));\ns1r = s1r(0.5*N+1:end-0.5*N);\n\n% s2 Shifting By Fourier Property\nS2 = fftshift(fft(ifftshift(s2))); \nS2 = S2.*exp(1j*2*pi.*fa2.*time_delay); \ns2r = fftshift(ifft(ifftshift(S2)));\ns2r = s2r(0.5*N+1:end-0.5*N);\n\nResult = s1r - s2r;\n\n\nfigure(1);\nplot(ta,abs(Result)); xlabel(&quot;t(s)&quot;);\ntitle('After Substraction');\n</code></pre>\n<p>However, the result is the following picture:</p>\n<p><img src="https://i.sstatic.net/JNB1rT2C.png" alt="Graph of the result of the Fourier transform" /></p>\n<p>The center part is quite low, but the two sides are very high and I think this is because the signals are aliasing. I don't know how to fix this problem. I would greatly appreciate any guidance or suggestions to help me resolve this issue.</p>\n"^^ . . "1"^^ . "ti-dsp"^^ . . . . . "@3CxEZiVlQ : The tag was incorrectly removed from the posting by Wolfie. A stl is a graphic format and is what the OP needs."^^ . "Save a structure in MATLAB data dictionary"^^ . . "If you change `line_segments(2,4) = 5.551825`, you'll get parallel lines. There's nothing wrong with your code, it's the data."^^ . "<p>I'm having this error but I don't understand why. I'm creating a structure of size 3x4x4 with 6 fields within loops. Then, I would like to create two more fields for the whole structure. How can I do it?</p>\n<pre><code>for i = 1:N\n for j=1:length(Cr)\n for m=1:length(TR)\n for k=1:length(pH)\n form(j,m,k).name = [&quot;c&quot; num2str(Cr(j)) &quot;TR&quot; num2str(TR(m)) &quot;ph&quot; num2str(pH(k))];\n form(j,m,k).Cr = Cr(j);\n form(j,m,k).Ct = Cr(j)*TR(m); % corde tip\n form(j,m,k).S = (form(j,m,k).Cr+form(j,m,k).Ct)*H/2;\n form(j,m,k).AR = H^2./form(j,m,k).S;\n if (pH(k) == 0)\n form(j,m,k).c(i) = form(j,m,k).Ct*cos(phi(i))+form(j,m,k).Cr*(1-cos(phi(i)));\n elseif (yh(i) &lt; H*pH(k))\n form(j,m,k).c(i) = form(j,m,k).Cr;\n else\n form(j,m,k).c(i) = form(j,m,k).Cr+(form(j,m,k).Ct-form(j,m,k).Cr)/(H-pH(k)*H)*(yh(i)-pH(k)*H);\n endif\n end\n end\n end\nend\n\nform.c_top = form.c(N/2+1:end);\nform.c_bot = form.c(1:N/2);\n</code></pre>\n<p>I would like that form(x,y,z).c_top = form(x,y,z).c(N/2+1:end), and this for the whole structure.</p>\n"^^ . "0"^^ . "0"^^ . . . . "1"^^ . . . . . . "<p>I looks like <code>R.matlab</code> is doing you a favour by omitting those characters. While I am not an SME, an internet search suggests those characters are often omitted from the affected species names so perhaps they are errors? At least there are only seven to deal with if you have to manually edit them.</p>\n<p>To examine the issue, you can use the <code>rmatio</code> package, as it will retain the non-UTF characters.</p>\n<pre class="lang-r prettyprint-override"><code>library(rmatio)\nlibrary(stringi)\n\n# Unzip .mat previously downloaded from\n# https://azti.sharepoint.com/sites/Proyectos/AMBI/Documentos%20compartidos/Forms/AllItems.aspx?id=%2Fsites%2FProyectos%2FAMBI%2FDocumentos%20compartidos%2FLibrary%2D2024%2Ezip&amp;parent=%2Fsites%2FProyectos%2FAMBI%2FDocumentos%20compartidos&amp;p=true&amp;ga=1\n# Edit file path where necessary\nunzip(&quot;data/AMBI/Library-2024.zip&quot;,\n files = &quot;library.mat&quot;,\n exdir = &quot;data/AMBI/&quot;)\n\nambi &lt;- read.mat(&quot;data/AMBI/library.mat&quot;)\n\n# Convert to df\ndf &lt;- data.frame(name = unlist(ambi$specieslist$name),\n group = unlist(ambi$specieslist$group),\n reassign = unlist(ambi$specieslist$reassign))\n\n# Return rows containing non-UTF\nx &lt;- df[which(stri_enc_mark(df$name) == &quot;native&quot;),]\n\nx$name\n# [1] &quot;Congetia chesneyi\\xfd&quot; &quot;Erythrops go\\xfdsi&quot; &quot;Erythrops go\\xfdsii&quot; \n# [4] &quot;Gymnonereis\\xfdcrosslandi&quot; &quot;Hippolyte cura\\xfdaoensis&quot; &quot;Neorhynchoplax\\xfdsp.&quot; \n# [7] &quot;Valencinia\\xfdsp.&quot;\n\n# Convert non-UTF chars\niconv(x$name, from = &quot;macroman&quot;, to = &quot;UTF-8&quot;)\n# [1] &quot;Congetia chesneyi˝&quot; &quot;Erythrops go˝si&quot; &quot;Erythrops go˝sii&quot; \n# [4] &quot;Gymnonereis˝crosslandi&quot; &quot;Hippolyte cura˝aoensis&quot; &quot;Neorhynchoplax˝sp.&quot; \n# [7] &quot;Valencinia˝sp.&quot;\n</code></pre>\n<p>The closest encoding I could find was &quot;macroman&quot; but it is still not correct. Again, not an SME, but it appears that in some cases, those non-UTF characters are supposed to be either a &quot;ë&quot;, or not there at all. If there is uncertainty, the only thing I can suggest is to contact the data maintainers to find out the correct encoding, or whether these are indeed errors. At least then you can rule out whether it's something to do with R.</p>\n"^^ . "0"^^ . "<p>I have error on part of code that called the preprocess lib.</p>\n<p>I tried main site and chat gpt but :) nothing for this part:</p>\n<pre><code>for i1=1:L\n I=imread([FOLDEROpen ImagesName(i1).name]);\n\n [I X_]=PreProcess( I,Size1,Nbins,NWindow,NWindow ); \n X(fol,:,i1)=X_;\n</code></pre>\n"^^ . "2"^^ . "0"^^ . . . "0"^^ . . . . "0"^^ . . . . . . "basis"^^ . . . . . . . . "also to notify everyone, the most efficient answer by far that was recommended to me was [James Tursa's mex file](https://www.mathworks.com/matlabcentral/answers/2174161-need-to-vectorize-efficiently-calculating-only-certain-values-in-the-matrix-multiplication-a-b-us#answer_1560085) that does "masked matrix multiplication", and apparently "masked matrix multiplication" is a well defined concept so I will be looking into that. Thank you everyone for your help"^^ . "Undocumented `hittest` no longer working as expected"^^ . . "linear-programming"^^ . . . "0"^^ . "Try the back tick instead backward slash."^^ . . . "-1"^^ . "0"^^ . . "2"^^ . . . "matlab-table"^^ . "I edited the question, should be clearer now @Wolfie"^^ . "0"^^ . . "1"^^ . . . . "1"^^ . . "<p>I successfully integrated MATLAB &amp; R in macOS with Homebrew and Xcode Build Server (Apple Silicon). I made a step-by-step for that.</p>\n<p>However, I am failing when trying to do the same in Windows 10, and I am failing... successfully as well. I tried to make the same step-by-step.</p>\n<p>(1) Open PowerShell as Administrator</p>\n<ul>\n<li>Press Windows + S.</li>\n<li>Type PowerShell.</li>\n<li>Right-click on Windows PowerShell → Run as administrator.</li>\n</ul>\n<p>(2) Run the Command Again</p>\n<ul>\n<li>Now, with administrator permissions, run:</li>\n</ul>\n<pre><code>Set-ExecutionPolicy Bypass -Scope Process -Force;\n[System.Net.WebClient]::new().DownloadString('https://community.chocolatey.org/install.ps1') | Invoke-Expression\n</code></pre>\n<p>This will correctly install Chocolatey.</p>\n<p>(3) Verify the Installation\nOnce finished, check if it works by running:</p>\n<pre><code>choco --version\n</code></pre>\n<p>Expected output:</p>\n<pre><code>2.4.2 (or a similar version)\n</code></pre>\n<p>INSTALL THE REQUIRED TOOLS</p>\n<p>(1) Now install the tools MATLAB needs:</p>\n<pre><code>choco install gnuwin32-coreutils.install -y\n</code></pre>\n<p>(2)</p>\n<ul>\n<li>Check the Location of the expr.exe File</li>\n<li>Open PowerShell as Administrator.</li>\n<li>Run the following command:</li>\n</ul>\n<pre><code>dir &quot;C:\\&quot; -Recurse -Filter expr.exe -ErrorAction SilentlyContinue\n</code></pre>\n<p>What does it do?\nIt searches for expr.exe across the C: drive.\nYou should see a path like:</p>\n<pre><code>C:\\Program Files (x86)\\GnuWin32\\bin\\expr.exe\n</code></pre>\n<p>(3) Add the Path to the System PATH\nIf the previous command returned a valid path, add it to the PATH:</p>\n<pre><code>setx PATH &quot;$($env:PATH);C:\\Program Files (x86)\\GnuWin32\\bin&quot;\n</code></pre>\n<p>(4) Verify that the PATH Includes expr.exe\nClose and reopen PowerShell.\nRun:</p>\n<pre><code>expr --version\n</code></pre>\n<p>Check if MATLAB is in the PATH</p>\n<pre><code>where matlab\n</code></pre>\n<p>If it doesn't return MATLAB's path, you need to add it manually.</p>\n<ul>\n<li>Add MATLAB to the PATH</li>\n<li>Find MATLAB’s bin folder, for example:</li>\n</ul>\n<pre><code>C:\\Program Files\\MATLAB\\R2024b\\bin\n</code></pre>\n<p>Open PowerShell as Administrator and run:</p>\n<pre><code>setx PATH &quot;$($env:PATH);C:\\Program Files\\MATLAB\\R2024b\\bin&quot;\n</code></pre>\n<p>Close and reopen PowerShell.\nFinal Step: Restart MATLAB\nRestart the computer if necessary.\nOpen MATLAB as Administrator.</p>\n<p>Then, in macOS I had the following code and worked:</p>\n<pre><code># install.packages(&quot;R.matlab&quot;)\nlibrary(R.matlab)\n\n# system(&quot;matlab -nodesktop -nosplash -r \\&quot;disp('MATLAB works!');exit;\\&quot;&quot;)\n\n# Save MATLAB code to file\nmatlab_code &lt;- &quot;\n% MATLAB Model\n\n% Parameters\nalpha1 = 0.315; alpha2 = 0.100; alpha3 = 0.585;\nbeta = 0.95; sigma = 0.40; deltak = 0.06;\ndeltag = 0.05; rho = 0.95;\n\n% Initial Values\nY = 1; C = 0.75; L = 0.3; K = 3.5;\nI = 0.25; G = 1; z = 1; e = 0;\ntau = 0.25; tauA = 0.22; lamda = 0.0303;\n\n% Model Equations\nfor t = 1:1000\n Y = z*(K^alpha1)*(G^alpha2)*(L^alpha3);\n C = (sigma/(1-sigma))*(1-L)*(1-tau)*((alpha3/(alpha1+alpha3))*Y/L);\n K = (Y - C) + (1 - deltak) * K;\n G = lamda * Y + (1 - deltag) * G;\n I = Y - C - (lamda * Y);\n z = exp(rho * log(z) + randn * 0.01);\nend\n\n% Display results\ndisp(['Final Output: ', num2str(Y)]);\n&quot;\nwriteLines(matlab_code, &quot;model.m&quot;)\n\n# Run MATLAB script and capture output\nmatlab_output &lt;- system(&quot;matlab -nodesktop -nosplash -r \\&quot;run('model.m'); exit;\\&quot;&quot;, intern = TRUE)\n\n\n# Print output for debugging\nprint(matlab_output)\n\n# Find the line containing &quot;Final Output:&quot;\nfinal_line &lt;- grep(&quot;Final Output:&quot;, matlab_output, value = TRUE)\n\n# Extract the numeric part using a regular expression\nfinal_value &lt;- as.numeric(sub(&quot;Final Output: &quot;, &quot;&quot;, final_line))\n\n# Print extracted value\nprint(final_value)\n</code></pre>\n<p>In Windows, R opens MATLAB displays the result but does not capture it and bring it to the environment.</p>\n<pre><code>matlab_output &lt;- system(&quot;matlab -nodesktop -nosplash -r \\&quot;run('model.m'); exit;\\&quot;&quot;, intern = TRUE)\n\n</code></pre>\n"^^ . "0"^^ . . . . . "I made some quick test and quite confirm above suspisions ... so i think i can workaround by temporarely replacing `WindowButtonMotionFcn` in `addlistener` event listener and restore everything at the end of the call ... I will make more clean code for workaround i'm thinking of."^^ . "0"^^ . . . "0"^^ . "@LuisMendo In figure 2, only the slow increase on the left needs consideration; regions with y>1e4 need be ignored."^^ . . "0"^^ . "When on remote desktop, Matlab creates a figure that is for half outside of the screen"^^ . . . . "linear-regression"^^ . . "c"^^ . . . . . "0"^^ . . . "2"^^ . . "Hm. yes but cell array of object is allowed.."^^ . "0"^^ . . . "noise"^^ . "Can I get raw camera data in matlab (before any conversion)"^^ . "Draw decision boundary using Polynomial Kernel Function in SVM Matlab"^^ . . "Its inbuilt function so you can find it above. There is just issue with the just matrix multiplication in Task 5 snippet mention here. please use any data sets for that code."^^ . . "1"^^ . . "chtz, pt 1: Yes! What you wrote using repmat is equivalent to expressing L as a Kronecker product of some matrix of 1s (e.g. ones(3,4)) with some smaller binary matrix you can call "L_block". The matrix of 1s can be any sized matrix of 1s (including ones(1)). I sort of exploited this kronecker product structure to perform my original post's solution under "Possible solution (need help vectorizing this code if possible)"."^^ . . "What driver support **does** the camera manufacturer provide on your platform? Which make, model and resolution is it? This sounds like Matlab not having recognised the camera properly and is making invalid assumptions about the data stream."^^ . . "How big is your actual array? Because 5000x1 is tiny and it's not worth using a sparse array for. You need much, much larger arrays to make the sparse array overhead worth while."^^ . . . . . . . . . "The Wikipedia article on the topic is using the plane equation `ax+by+cz=d`, but my (and I believe yours as well, as we output the same coefficients) example uses the form `ax+by+cz+d=0`. When switching between them, the sign of `d` is flipped. Let me know if you find otherwise; I really don't mean to argue over semantics. Thanks for the dialogue!"^^ . . "<p>I have matrices <strong>A</strong> (m by v) and <strong>B</strong> (v by n). I also have a logical matrix <strong>L</strong> (m by n).</p>\n<p>I am interested in calculating only the values in <strong>A</strong> * <strong>B</strong> that correspond to logical values in <strong>L</strong> (values of 1s). Essentially I am interested in the quantity ( <strong>A</strong> * <strong>B</strong> ) .* <strong>L</strong> .</p>\n<p>For my problem, a typical L matrix has less than 0.1% percent of its values as 1s; the vast majority of the values are 0s. Thus, it makes no sense for me to literally perform ( <strong>A</strong> * <strong>B</strong> ) .* <strong>L</strong> , it would actually be faster to loop over each row of <strong>A</strong> * <strong>B</strong> that I want to compute, but even that is inefficient.</p>\n<hr />\n<p><strong>Possible solution (need help vectorizing this code if possible)</strong></p>\n<p>My particular problem may have a nice solution given that the logical matrix <strong>L</strong> has a nice structure.</p>\n<p>Here's an example of L for a very small scale example (in most applications L is much much bigger and has much fewer 1-yellow entries, and many more 0-blue entries).\n<img src="https://i.imgur.com/P4TLMiG.png" alt="" /></p>\n<p>This L matrix is nice in that it can be represented as something like a permuted block matrix. This L in particular is composed of 9 &quot;blocks&quot; of 1s, where each block of 1s has its own set of row and column indices, defining a particular submatrix in <strong>A</strong> * <strong>B</strong>. For instance, the highlighted area here can be seen the values of 1 as a particular submatrix in L.\n<img src="https://i.imgur.com/JjsoeW0.png" alt="" /></p>\n<p>My solution was to do this: break the problem into submatrices over these blocks, and do matrix multiplications over each submatrix. I can get the row indices and column indices per each block's submatrix in L, organized in two cell lists &quot;rowidxs_list&quot; and &quot;colidxs_list&quot;, both with the number of cells equal to the number of blocks. For instance in the block example I gave, subblock 1, I could calculate those particular values in A * B by simply doing A( rowidxs_list{1} , : ) * B( : , colidxs_list{1} ) .</p>\n<p>That means that if I precomputed rowidxs_list and colidxs_list (ignore the costs of calculating these lists, they are negligable for my application), then my problem of calculating <strong>C</strong> = ( <strong>A</strong> * <strong>B</strong> ) .* <strong>L</strong> could effectively be done by:</p>\n<pre><code>C = sparse( m,n )\nfor i = 1:length( rowidxs_list )\n C( rowidxs_list{i} , colidxs_list{i} ) = ...\n A( rowidxs_list{i} , : ) * B( : , colidxs_list{i} );\nend\n</code></pre>\n<p>This seems like it would be the most efficient way to solve this problem <strong>if I knew how to vectorize this for loop</strong>. Does anyone see a way to vectorize this?</p>\n<p>There may be ways to vectorize if certain things hold, e.g. only if rowidxs_list and colidxs_list are matrix arrays instead of cell lists of lists (where each column in an array is an index list, thus replacing use of rowidxs_list{i} with rowidxs_list(i,:) ). I'd prefer to use cell lists here if possible since different lists can have different numbers of elements.</p>\n<hr />\n<p><strong>other suggested solution (creating a mex file?)</strong></p>\n<p>I first posted this question on the /r/matlab subreddit, <a href="https://www.reddit.com/r/matlab/comments/1iro2m4/need_to_vectorize_efficiently_calculating_only/" rel="nofollow noreferrer">see here for the reddit thread</a>. The user &quot;qtac&quot; recommended that a C-MEX function linking to C programming language:</p>\n<blockquote>\n<p>My gut feeling is the only way to really optimize this is with a C-MEX solution; otherwise, you are going to get obliterated by overhead from subsref in these loops. With C you could loop over L until you find a nonzero element, and then do only the row-column dot product needed to populate that specific element. You will miss out on a lot of the BLAS optimizations but the computational savings may make up for it.\nHonestly I bet an LLM could write 90%+ of that MEX function for you; it's a well-formulated problem.</p>\n</blockquote>\n<p>I think this could be a good solution to pursue, but I'd like other opinions as well.</p>\n"^^ . . "0"^^ . "to magnesium, chtz and Louis, , pt 1: yes regarding magnesium's comment, my solution in the original post (under "Possible solution (need help vectorizing this code if possible)") was me trying to exploit the periodicity of L. It can be shown that L is made up of a small number of submatrix "blocks": submatrices where all values are 1, in the example image I gave there are 9 blocks. So my solution (I'll call it "blocklooping") was to go over each block, and have a submatrix multiplication like A(rowidxs,:) * B(:,colidxs) to construct each block in C."^^ . "0"^^ . . "<p>I am modeling a radar image based on my already modeled field of sea surface waves. Faced with the problem that the final image does not work right. It turns out to be some kind of nonsense. You can see the resulting image and what the field of surface waving looks like.<a href="https://i.sstatic.net/LR9XrYLd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LR9XrYLd.png" alt="RADAR image" /></a><a href="https://i.sstatic.net/AJrIfG78.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AJrIfG78.png" alt="Surface Waving field" /></a></p>\n<p>The script in MATLAB looks like this (without taking into account main_prog from which all these functions are called).</p>\n<p>Functions of parameters:</p>\n<pre><code>function [g, speed, dx, dy, x, y, df, f_start, f_end, dtt, theta] = common_data() \n g = 9.81; % acceleration of gravity\n speed = 13; % wind speed\n\n dx = 1; % step along the x-axis\n dy = 1; % step along the y-axis\n x = 0:dx:1000; \n y = 0:dy:1000; \n\n df = 0.1; % frequency range step\n f_start = 0.016; % frequency range start\n f_end = 1.25; % frequency range end\n\n dtt = pi / 18; % angle step \n theta = -pi/2:dtt:pi/2; % angle range\nend\n\nfunction [xd, alpha, wmaxd, wmax, gm] = JONSWAP_param(g, speed)\n xd = 2 * 10^(4); % acceleration parameter\n alpha = 0.076 * xd^(-0.22); % Phillips constant\n wmaxd = 3.5 * xd^(-0.33); % dimensionless frequency\n wmax = wmaxd * (g / speed); % max frequency of spectrum\n gm = 3.3; % gamma-factor\nend\n</code></pre>\n<p>Spectrum calculations:</p>\n<pre><code>function [JSP] = JONSWAP_Spec(g, alpha, wmax, gm, f)\n sgm = zeros(size(f)); \n EXP = zeros(size(f)); \n JSP = zeros(size(f)); \n \n for i = 1:length(f)\n if wmax &gt;= f(i) \n sgm(i) = 0.07; \n else\n sgm(i) = 0.09; \n end\n \n EXP(i) = exp(- ( (f(i) - wmax)^2 ) / ( 2 * sgm(i)^2 * wmax^2) ); \n JSP(i) = alpha * g^(2) * (2*pi)^(-4) * ( (f(i))^(-5) ) * ( exp( (-5/4) * (f(i)/wmax)^(-4) ) ) * ( gm^(EXP(i)) ); % JONSWAP spectrum\n end \nend\n\nfunction [St, Swt, eta0] = Freq_Ang_Spec(dtt, theta, df, JSP)\n St = cos(theta).^(4); % angular spectrum\n Norm = trapz(dtt, St); \n\n Swt = JSP .* St'; % freq-angular spectrum\n \n eta0 = sqrt((2 * Swt .* df * dtt) ./ Norm); % amplitude of surface waving \nend\n</code></pre>\n<p>Surface Waving simulation:</p>\n<pre><code>function [phase, Kx, Ky, etaWA] = SurfaceWaving_simulator(g, x, y, theta, w, eta0)\n phase = 2*pi*rand(length(theta),length(w)); % initial phase\n\n t = 0; % time moment\n\n Kabs = (w.^2) / g; % wavenumber \n Kx = Kabs .* cos(theta)'; % projection of the wavevector on the x-axis \n Ky = Kabs .* sin(theta)'; % projection of the wavevector on the y-axis \n \n etaWA = zeros(length(x),length(y)); \n \n for i = 1:length(x)\n for j = 1:length(y)\n etaWA(i,j) = sum(eta0 .* cos(w * t - Kx * i - Ky * j + phase), 'all');\n end\n end\nend\n</code></pre>\n<p>RADAR data and RADAR image simulation:</p>\n<pre><code>function [az_ang, inc_ang, slope_x, slope_y, Rfl_VV_s, Rfl_HH_s, K_rad, K_b, f_b] = Geom_Sig_Settings(g, x, y, etaWA)\n H_rad = 14; % radar height above sea level\n\n r = sqrt(x.^2 + y.^2); % horizontal distance \n R = sqrt(r.^2 + H_rad^2); % the trajectory of the signal to each point of the surface\n\n az_ang = atan2(y, x); % azimuth angle of the radar\n inc_ang = acos(H_rad./R); % angle of incidence \n graz_ang = pi/2 - inc_ang; % grazing angle \n\n % Calculation of local surface slopes (geometric modulation of the returned signal)\n [sx, sy] = gradient(etaWA);\n slope_x = atan(sx); % slope on x\n slope_y = atan(sy); % slope on y\n % Converting slopes to the radar coordinate system\n slope_rad_x = slope_x .* cos(az_ang) + slope_y .* sin(az_ang); \n slope_rad_y = -slope_x .* sin(az_ang) + slope_y .* cos(az_ang);\n\n % Calculation of geometric reflection coefficients \n Rfl_VV = @(inc_ang) (cos(inc_ang)).^(4) .* (1 + (sin(inc_ang)).^(2)).^(2) / (cos(inc_ang) + 0.111).^(4); % the square of the reflection coefficient module (case VV)\n Rfl_HH = @(inc_ang) (cos(inc_ang)).^(4) / (0.111 .* cos(inc_ang) + 1).^(4); % the square of the reflection coefficient module (case HH)\n\n Rfl_VV_s = sqrt(Rfl_VV(inc_ang + slope_rad_x)); % reflection coefficient module (case VV)\n Rfl_HH_s = sqrt(Rfl_HH(inc_ang + slope_rad_x)) + (slope_rad_y / sin(inc_ang)).^(2) .* sqrt(Rfl_VV(inc_ang)); % reflection coefficient module (case HH)\n\n %% Radar signal parameters\n c_light = 3 * 10^(8); % light speed\n f_rad = 10 * 10^(9); % the frequency of the radar signal emitted by the radar\n lambda_rad = c_light / f_rad; % the wavelength of the radar signal\n K_rad = (2*pi) / lambda_rad; % the wavenumber of the radar signal\n\n K_b = 2 * K_rad * sin(inc_ang); % the Bragg-Wolfe condition\n sigma = 0.073 / 997; \n f_b = sqrt(g * K_b + sigma * (K_b).^(3)) / (2*pi); % frequency of Bragg waves\nend\n\nfunction [JSP_b, RCS_VV] = RadBackscat_Simulator(g, alpha, wmax, gm, az_ang, Rfl_VV_s, Rfl_HH_s, K_rad, K_b, f_b)\n % Calculation of JONSWAP spectrum using f_B\n JSP_b = JONSWAP_Spec(g, alpha, wmax, gm, f_b);\n\n RCS_VV = 16 * pi * (K_rad)^4 .* (abs(Rfl_VV_s))^2 .* JSP_b; \n\n %RCS_HH = 16 * pi * (K_rad)^4 .* (abs(Rfl_HH_s))^2 .* JSP_b;\n\n %% Radar image visualization\n figure(3)\n imagesc(log10(RCS_VV));\n colormap gray;\n colorbar;\n title('RADAR image');\n xlabel('x');\n ylabel('y');\nend\n</code></pre>\n<p>At the moment, I'm not sure what the problem might be, but nothing else comes to mind. I think the whole problem lies in the fact that my model does not take into account the position of the radar, because depending on the azimuthal angle <code>az_ang</code> and angle of incidence <code>inc_ang</code> at which the radar &quot;looks&quot; at a particular point on the ocean surface, the slope values <code>slope_x</code> <code>slope_y</code> will depend. That is, in fact, if we change the position of the radar, it will also change slopes. In my case, the slopes are counted without taking this fact into account.</p>\n<p>I tried to take this fact into account when calculating the slopes, but it didn't give any results:</p>\n<pre><code> % Converting slopes to the radar coordinate system\n slope_rad_x = slope_x .* cos(az_ang) + slope_y .* sin(az_ang); \n slope_rad_y = -slope_x .* sin(az_ang) + slope_y .* cos(az_ang);\n</code></pre>\n<p>What am I doing wrong? What could be the problem?</p>\n<p>I took the formulas for reflection coefficients here ( page 3 formulas (3),(4) &amp; (6),(7) ):</p>\n<p><a href="https://www.researchgate.net/publication/47652627_A_semiempirical_model_of_the_normalized_radar_cross-section_of_the_sea_surface_-_1_Background_model" rel="nofollow noreferrer">https://www.researchgate.net/publication/47652627_A_semiempirical_model_of_the_normalized_radar_cross-section_of_the_sea_surface_-_1_Background_model</a></p>\n"^^ . . . . . . "0"^^ . . . "1"^^ . . . "0"^^ . . . "@463035818_is_not_an_ai Could you also format what is quoted accordingly?"^^ . "<p>Suppose that I have a function defined on 0&lt;= x&lt;= pi, 0&lt;=y, z&lt;=2pi.\nI have written a matlab code to global search the maximum point, with step length 0.01.\nI also restored the function value.\nThe code is (of course the function is more complicated than x+y+z. This is simply an example.)</p>\n<pre><code>x=0;\ny=0;\nz=0;\ni=1;\n\nMaxdeviation= ComputeDeviationSum(0,0,0,mufT, mufD, mufC);\nMaximizingArg= [x, y,z] ;\nwhile x&lt;= pi\n y=0;\n z=0;\n while y&lt;= 2*pi\n z=0;\n while z&lt;=2 *pi\n deviation= x+y+z; % Just an example. The function is more complex.\n if deviation&gt; Maxdeviation\n MaximizingArg= [x, y,z];\n Maxdeviation= deviation;\n end\n a(i,:)=[x, y,z, deviation];\n z=z+0.01;\n i=i+1;\n end\n y=y+0.01;\n end\n x=x+ 0.01;\nend\n</code></pre>\n<p>And I found this really slow. After I deleted the three lines restoring the value, i.e. deleted</p>\n<pre><code>i=1;\na(i,:)=[x, y,z, deviation];\ni=i+1\n</code></pre>\n<p>these three lines, it became much faster. (I stopped the execution after 20 seconds and found the latter did 10 times more iteration than the former.)</p>\n<p>My question is: Why after stopping restoring value, the code is much faster?\nWhat should I do to let the code be faster if I want to restore the value for each point?</p>\n"^^ . . . . . . . . . . . "<p>I have a Excel file with names of variables and their associated values as columns ash shown below:\n<a href="https://i.sstatic.net/oTpEkeQA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oTpEkeQA.png" alt="Parameter table in Excel" /></a></p>\n<p>I would like to use them in my Simulink model as inputs, therefore I need them to load as variables individually and not as a table or an array.</p>\n<p>Please help me in achieving the following results in MATLAB workspace</p>\n<p><a href="https://i.sstatic.net/6M8f3cBM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6M8f3cBM.png" alt="MATLAB Workspace" /></a></p>\n<p>Thank you in advance.</p>\n<p>Moreover, if the file type needs to be changed to CSV or txt format, I could explore the option.</p>\n<p>P.S. I am not using dynamic variable evaluation. These are fixed parameters to be fed to the model.</p>\n"^^ . . "0"^^ . . "<p>I recently started working with data dictionaries in Matlab Simulink as it a efficient way to manage the data. I could assign entries for Matlab parameters etc.; however, I am trying to save a structure containing table data (multiple tables) in a data dictionary. The problem is if I simply add an entry using <code>addEntry</code>, I longer can access the internal tables and could see their values or names. Whereas I tried to add Datatype in Architectural section of data dictionary but I can't assign it in design data.</p>\n<p>So is there any way that I can assign a <code>1X1 struct</code> with 7 fields containing tables in the design data section of data dictionary or I should assign the columns of tables to different variables in base workspace to save them as Matlab parameters by using <code>addEntry</code>?</p>\n<p>Sample code:</p>\n<pre><code>DictionaryFile='myDictionary.sldd';\nmyDictionaryObj = Simulink.data.dictionary.open(DictionaryFile);\ntoolDataSectObj=getSection(myDictionaryObj,'Design Data');\naddEntry(toolDataSectObj,'TableData',TableStrucutre);\n</code></pre>\n<p>Thank you.</p>\n"^^ . . . . "1"^^ . "1"^^ . . . . . . "<pre><code>Flag = 0;\n\nwhile Flag == 0\n for x = 1:10\n if x == 3\n Flag = 1;\n end % end: if\n end % end; for\nend % end: while\n</code></pre>\n<p>Can anyone tell me why the while loop condition is not triggering when x is three? It runs the entire for loop and I get a value of 10. I am trying to have a flag trigger when a specific condition is met in the for loop.</p>\n<p>Thank you!</p>\n"^^ . "mcc"^^ . "<p>I am fairly new to matlab and I managed to create a simulink model that tracks estimates using kalman filtering for position of drone but now I am supposed to implement A* Algorithm with my model, while I understand the Algorithm provided by the Matlab study, I dont know how I can connect it with my model. For reference, This is the reference generator ( movement control ) for my drone system <a href="https://i.sstatic.net/51sE59RH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/51sE59RH.png" alt="Reference Generator Image from My Simulink Model" /></a></p>\n<p>and the Algorithm files I am using are from this link <a href="https://www.mathworks.com/matlabcentral/fileexchange/26248-a-a-star-search-for-path-planning-tutorial" rel="nofollow noreferrer">https://www.mathworks.com/matlabcentral/fileexchange/26248-a-a-star-search-for-path-planning-tutorial</a></p>\n"^^ . . . . "0"^^ . "Looks like you neither understood the [edit] nor the "add .. to the question" nor the "I will do thast for you..."."^^ . . . "0"^^ . . "mingw-w64"^^ . "Indeed, I did some quick benchmarks and looks like `abs` does have sufficient overhead to makes the loop (without `sub2ind` as suggested by Cris in the comments) faster for a generic array, while this might be quicker for positive arrays"^^ . . . "2"^^ . . . "1"^^ . . "2"^^ . . "0"^^ . . "cuda"^^ . . . "Fastest way to find first ZERO element of a sparse matrix"^^ . "0"^^ . . "1"^^ . "1"^^ . . . . . . . "svm"^^ . . . . . . "2"^^ . . "system"^^ . . "constants"^^ . "performance"^^ . . "<p>I am trying to convert a matlab function to its equivalent CUDA MEX function. Below is the matlab function:</p>\n<pre><code>function [ShiftData_time] = simpledelayupdated_mat(RData, delay, fs)\n nfft = size(RData,1);\n binStart = floor(nfft/2);\n fftBin = (2*pi*ifftshift(((0:nfft-1)-binStart).'))/nfft; \n fftBin = fftBin';\n \n RFFT = fft(RData, nfft, 1);\n ShiftData = RFFT .* ((exp(-1i * delay * fftBin)).'); \n ShiftData_time = ifft(ShiftData, nfft, 1);\n ShiftData_time = real(ShiftData_time);\nend\n</code></pre>\n<p>Here is the CUDA implementation using MEX :</p>\n<pre><code>#include &quot;mex.h&quot;\n#include &lt;cuda_runtime.h&gt;\n#include &lt;cufft.h&gt;\n#include &lt;math.h&gt;\n#define M_PI 3.14159\n\n// Macro for cuFFT error checking.\n#define CUFFT_CHECK_ERROR(call) { cufftResult err = call; if(err != CUFFT_SUCCESS) { \\\n mexErrMsgIdAndTxt(&quot;CUDA:CUFFTError&quot;, &quot;CUFFT error: %d&quot;, err); } }\n\n// Macro for CUDA runtime error checking.\n#define CUDA_CHECK_ERROR(call) { cudaError_t err = call; if(err != cudaSuccess) { \\\n mexErrMsgIdAndTxt(&quot;CUDA:RuntimeError&quot;, &quot;CUDA error: %s&quot;, cudaGetErrorString(err)); } }\n\n// Updated CUDA kernel to apply the phase shift (delay) in the frequency domain.\n// Instead of launching one block per column with nfft threads, we now use a 2D grid.\n// grid.x corresponds to the column index, and grid.y is the number of blocks needed\n// to cover all frequency bins (with a fixed block size).\n__global__ void applyDelay(cufftDoubleComplex *data, const double *fftBin, double delay, int nfft, int nCols)\n{\n int col = blockIdx.x; // Column index.\n int blockId = blockIdx.y; // Block index within the column.\n int threadsPerBlock = blockDim.x;\n int threadId = threadIdx.x;\n\n // Compute global frequency bin index within this column.\n int index = blockId * threadsPerBlock + threadId;\n \n if (col &lt; nCols &amp;&amp; index &lt; nfft)\n {\n int idx = col * nfft + index;\n double phase = -delay * fftBin[index];\n double cosPhase = cos(phase);\n double sinPhase = sin(phase);\n \n cufftDoubleComplex factor;\n factor.x = cosPhase;\n factor.y = sinPhase;\n \n cufftDoubleComplex orig = data[idx];\n cufftDoubleComplex result;\n result.x = orig.x * factor.x - orig.y * factor.y;\n result.y = orig.x * factor.y + orig.y * factor.x;\n data[idx] = result;\n }\n}\n\n// The MEX gateway function.\nvoid mexFunction(int nlhs, mxArray *plhs[],\n int nrhs, const mxArray *prhs[])\n{\n // Check input count: RData, delay, fs.\n if(nrhs != 3)\n mexErrMsgIdAndTxt(&quot;MATLAB:simpledelayupdated:invalidNumInputs&quot;, \n &quot;Three inputs required: RData, delay, fs.&quot;);\n \n // Ensure RData is real and double precision.\n if(!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]))\n mexErrMsgIdAndTxt(&quot;MATLAB:simpledelayupdated:inputNotDouble&quot;, \n &quot;RData must be real double precision.&quot;);\n \n // Get input RData and its dimensions.\n double *RData = mxGetPr(prhs[0]);\n mwSize nfft = mxGetM(prhs[0]); // Number of rows.\n mwSize nCols = mxGetN(prhs[0]); // Number of columns.\n \n // Read scalar inputs: delay and fs (fs is provided for compatibility).\n double delay = mxGetScalar(prhs[1]);\n double fs = mxGetScalar(prhs[2]); // Not used directly.\n \n // Create output array (real, same size as input).\n plhs[0] = mxCreateDoubleMatrix(nfft, nCols, mxREAL);\n double *ShiftData_time = mxGetPr(plhs[0]);\n \n // Allocate host memory for complex input data.\n cufftDoubleComplex *h_complex = (cufftDoubleComplex*) mxMalloc(nfft * nCols * sizeof(cufftDoubleComplex));\n for (mwSize col = 0; col &lt; nCols; col++) {\n for (mwSize row = 0; row &lt; nfft; row++) {\n int idx = col * nfft + row;\n h_complex[idx].x = RData[idx];\n h_complex[idx].y = 0.0;\n }\n }\n \n // Precompute the FFT frequency bins.\n // This corresponds to the MATLAB expression:\n // fftBin = (2*pi*ifftshift(((0:nfft-1)-floor(nfft/2))))/nfft\n double *h_fftBin = (double*) mxMalloc(nfft * sizeof(double));\n int binStart = (int)(nfft / 2);\n for (mwSize row = 0; row &lt; nfft; row++) {\n int shifted_idx = (row + binStart) % nfft;\n int centered = row - binStart;\n h_fftBin[shifted_idx] = (2.0 * M_PI * centered) / (double)nfft;\n }\n \n // Allocate device memory for the complex data and the fftBin vector.\n cufftDoubleComplex *d_data;\n CUDA_CHECK_ERROR(cudaMalloc((void**)&amp;d_data, nfft * nCols * sizeof(cufftDoubleComplex)));\n CUDA_CHECK_ERROR(cudaMemcpy(d_data, h_complex, nfft * nCols * sizeof(cufftDoubleComplex), cudaMemcpyHostToDevice));\n \n double *d_fftBin;\n CUDA_CHECK_ERROR(cudaMalloc((void**)&amp;d_fftBin, nfft * sizeof(double)));\n CUDA_CHECK_ERROR(cudaMemcpy(d_fftBin, h_fftBin, nfft * sizeof(double), cudaMemcpyHostToDevice));\n \n // Create a cuFFT plan for batched 1D FFTs (each column is one FFT of size nfft).\n cufftHandle plan;\n int rank = 1;\n int n[1] = {(int)nfft};\n int istride = 1, idist = nfft;\n int ostride = 1, odist = nfft;\n CUFFT_CHECK_ERROR(cufftPlanMany(&amp;plan, rank, n,\n NULL, istride, idist,\n NULL, ostride, odist,\n CUFFT_Z2Z, nCols));\n \n // Execute forward FFT (time to frequency domain).\n CUFFT_CHECK_ERROR(cufftExecZ2Z(plan, d_data, d_data, CUFFT_FORWARD));\n \n // Launch the CUDA kernel to apply the phase shift.\n int threadsPerBlock = 256; // Use a safe block size.\n int blocksPerColumn = (nfft + threadsPerBlock - 1) / threadsPerBlock;\n dim3 grid(nCols, blocksPerColumn, 1); // grid.x: columns, grid.y: blocks per column.\n dim3 block(threadsPerBlock, 1, 1);\n \n applyDelay&lt;&lt;&lt;grid, block&gt;&gt;&gt;(d_data, d_fftBin, delay, nfft, nCols);\n CUDA_CHECK_ERROR(cudaDeviceSynchronize());\n \n // Execute the inverse FFT to convert back to time domain.\n CUFFT_CHECK_ERROR(cufftExecZ2Z(plan, d_data, d_data, CUFFT_INVERSE));\n \n // Allocate host memory for the inverse FFT result and copy from device.\n cufftDoubleComplex *h_result = (cufftDoubleComplex*) mxMalloc(nfft * nCols * sizeof(cufftDoubleComplex));\n CUDA_CHECK_ERROR(cudaMemcpy(h_result, d_data, nfft * nCols * sizeof(cufftDoubleComplex), cudaMemcpyDeviceToHost));\n \n // Normalize the result by dividing by nfft and take the real part.\n for(mwSize i = 0; i &lt; nfft * nCols; i++) {\n ShiftData_time[i] = h_result[i].x / ((double)nfft);\n }\n \n // Clean up resources.\n cufftDestroy(plan);\n cudaFree(d_data);\n cudaFree(d_fftBin);\n mxFree(h_complex);\n mxFree(h_fftBin);\n mxFree(h_result);\n}\n</code></pre>\n<p>This is how I am calling the Matlab function:</p>\n<pre><code>[temp] = simpledelayupdated(gather(RF_Arr_gpu), scalarDelay, sampling_Freq);\n</code></pre>\n<p>where RF_arr_gpu is a 2D MATLAB gpuArray, scalarDelay and sampling_Freq are scalars.</p>\n<p>The issue I'm facing is that the final output from both functions does not match when run on real data. However, I have tested individual components of the CUDA MEX function, and the differences between the MATLAB and CUDA MEX outputs are minimal.</p>\n<p>Can anyone help me identify where there could be issues in the code? I have attached the output from MATLAB and what we are currently getting from CUDA MEX. The MATLAB image is continuous while the CUDA MEX seems to be more discrete.</p>\n<p><img src="https://i.sstatic.net/ikgxXlj8.png" alt="MATLAB image" />\n<img src="https://i.sstatic.net/Qs7B732n.png" alt="CUDA MEX image" /></p>\n"^^ . "0"^^ . "I've edited my question and provided my demo data and codes. Yes the output will have lot of zeros, as the number of element in each pixel of the 2d image will vary in a large range. Actually, what I'm dealing with is a FLIM (Fluorescence Lifetime Imaging Microscopy) dataset, and this conversion leads to a better adaptability for my following deep learning network training. It seems that my network cannot understand the histograms very well, so I'm thinking feeding those values directly into the network might help."^^ . "<p>Just putting the value of the constant block as a parameter does not expose it to external access since when the code is generated it will be buried somewhere with local scope accessibility.</p>\n<p>You need to use the <a href="https://ch.mathworks.com/help/simulink/slref/simulink.parameter.html" rel="nofollow noreferrer"><em>Simulink.Parameter</em></a> object. To do so keep the model as it is and create in the workspace a the object with the same name as the variable you are passing to the constant:</p>\n<pre><code>myCoinstantValue= Simulink.Parameter(); \nmyCoinstantValue.CoderInfo.StorageClass = 'ExportedGlobal';\n</code></pre>\n<p>The <em>ExportedGlobal</em> property is the one that exposes the parameter to external access by making the parameter a global variable in the generated code.</p>\n<p>There is other properties you can set as default value, data type, unit, ...</p>\n<p>You should now be able to pass it either using the <em>set_param</em> or using <em>system</em> commands as you would with any other .exe</p>\n"^^ . . . "0"^^ . . "<p>The ticklengths are both in your <code>ax1</code> (also both in your <code>ax2</code> which is the same as your <code>ax1</code>):</p>\n<pre><code>data = [2000 2010 2020;\n300 400 500;\n50 40 30;\n10 15 20];\nyyaxis left;\nb = bar(data(2:end-1,:)', &quot;stacked&quot;);\ncolororder('default')\nxticklabels(data(1, :));\nax1 = gca;\nax1.YGrid = &quot;on&quot;;\nyyaxis right;\nl = plot(data(end, :), 'k');\nl.LineWidth = 2;\nbox off\n\nax1.YAxis(1).Limits = [0 1000];\nax1.YAxis(2).Limits = [0 30];\nax1.YAxis(1).TickLength = [0 0];\nax1.YAxis(2).TickLength = [0 0];\n</code></pre>\n<p><a href="https://i.sstatic.net/OPqj0b18.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OPqj0b18.png" alt="enter image description here" /></a></p>\n"^^ . . "<p>In your code,</p>\n<pre class="lang-matlab prettyprint-override"><code>M = repmat(init, [1, length(r)]);\nM = r.*M + init;\n</code></pre>\n<p><code>r.*M</code> is identical to <code>r.*init</code>. Adding one <code>init</code> to that is the same as incrementing <code>r</code> by one first. So, your MATLAB code is the same as</p>\n<pre class="lang-matlab prettyprint-override"><code>M = (r + 1) .* init;\n</code></pre>\n<p>This version is about twice as fast. <code>repmat</code> is hardly ever useful anymore since MATLAB introduced implicit singleton expansion (a.k.a. broadcasting).</p>\n<p>The right way to time code that is very fast like this is using <a href="https://www.mathworks.com/help/matlab/ref/timeit.html" rel="nofollow noreferrer"><code>timeit</code></a>:</p>\n<pre class="lang-matlab prettyprint-override"><code>r = [1, 2, 3, 4, 5];\ninit = ones(9, 1);\ntimeit(@() func1(r, init))\ntimeit(@() func2(r, init))\n\nfunction M = func1(r, init)\nM = repmat(init, [1, length(r)]);\nM = r .* M + init;\nend\n\nfunction M = func2(r, init)\nM = (r + 1) .* init;\nend\n</code></pre>\n<p>Anyway, I am fairly sure that replicating this logic in Eigen will also produce much faster code. You will need to use <code>.array()</code>.</p>\n<blockquote>\n<p>On arrays, we can also use the operators <code>*=</code>, <code>/=</code>, <code>*</code> and <code>/</code> to perform coefficient-wise multiplication and division column-wise or row-wise. These operators are not available on matrices because it is not clear what they would do. [From <a href="https://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html" rel="nofollow noreferrer">&quot;Broadcasting&quot;</a>]</p>\n</blockquote>\n<p>But if your Eigen code took 13 seconds to run, then you surely are using a debug build. You should never time a debug build (especially of C++ code), they turn off most optimizations. With Eigen, optimization can easily make a 10x or even a 100x difference.</p>\n"^^ . "0"^^ . . . . . . . . "0"^^ . . . . "<p>I'm quite new to Matlab and I'm trying to convert 512*512 histograms to a 3d matrix. The following loop works fine but is quite slow especially when x and y increase. The timer in Matlab tells me that <code>repelem</code> function costs ~90% of time:</p>\n<pre><code>%% to generate input_hist\ninput_hist = zeros(512,512,3125,'uint16');\n[xdim, ydim, binNum] = size(input_hist);\nmax_count = 5000;\nfor x = 1:xdim\n for y = 1:ydim\n total_count = randi([0, max_count]);\n hist_vector = randi([0,31], 1, binNum);\n current_sum = sum(hist_vector);\n hist_vector = uint16(hist_vector * (total_count / current_sum));\n input_hist(x, y, :) = hist_vector;\n end\nend\n\nelementNum = sum(input_hist, 3);\nmaxElementNum = max(elementNum(:));\nminElementNum = min(elementNum(:));\n\n%% to generate values\nvalues = 4:4:12500;\nbinNum_ = length(values); % should be the same with binNum\n\n%% loops\ntic;\noutput_vals_loops = zeros(xdim, ydim, maxElementNum, 'single'); % fill with 0s\nfor x = 1:xdim\n for y = 1:ydim\n elementNumHere = elementNum(x,y);\n if elementNumHere &gt; 0\n valuesHere = repelem(values, squeeze(input_hist(x,y,:)));\n output_vals_loops(x,y,1:elementNumHere) = valuesHere;\n end\n end\nend\ntoc;\n</code></pre>\n<p><code>input_hist</code> is a 3d uint16 (512×512×3125), values is a vector (3125×1) corresponding to the 3rd demension of input_hist, <code>maxElementNum = ~500</code>0 and there are lots of zeros in <code>elementNum</code>.</p>\n<p>I searched the Internet but find no good solutions. Is there a faster way for me to do this conversion? 10X faster for example? Is it possible to avoid the loops? Or do I really have to use the function <code>repelem</code>?</p>\n"^^ . . . . . . . "0"^^ . . . "0"^^ . "@asdjkh, "the grayscale image created using my custom code have slightly different values. " --> What is an example those those different values? What was R,G,B?"^^ . . . . "Access datastore inside S-Function"^^ . . . "0"^^ . "0"^^ . . . . "0"^^ . . . . . . . . . . "3"^^ . "0"^^ . . . "Luis thanks for the nice vectorized solution, but I'm actually getting it slower than the other options.\n\nGiven the limited memory on my current computer, I tested your code with large data (my main concern case) for a certain large data size handleable by my computer. E.g., I tested when 2e-2% of the entries were 1s in L, and A * B was (m=5625 by n=90000). Here your method took around 63.1 seconds sec, vs 18.8 sec for (A * B) , and 28.5 sec for (A * B) .* L. this ratio was about the same for any value of v.\n\nI'm not clear why, maybe matlab is not that well optimized for indexing..."^^ . . . "training-data"^^ . . . . "0"^^ . . . "Can you also add a screenshot of the data you have in your spreadsheet?"^^ . "<p>As described in <a href="https://stackoverflow.com/a/31171332">this answer</a> (to the question you already linked in your question), the scalar box constraint <code>C</code> defines a penalty on the sum of slack variables. In the dual optimization problem, this corresponds to an upper bound to the Lagrange multipliers, hence the name &quot;Box Constraint&quot;. As you mention, this is a <em>scalar</em>, not a vector.</p>\n<p>The <code>BoxConstraints</code> property is, however, a <em>n</em>-by-<em>1</em> vector, where <em>n</em> is the number of training observations. Note that when calling <code>fitcsvm</code> you can only set <code>C</code> to a scalar and not a vector, so the <code>BoxConstraints</code> property is internally calculated.</p>\n<p>In the <a href="https://ch.mathworks.com/help/stats/fitcsvm.html#bt7oo83-5" rel="nofollow noreferrer">Algorithms section of the <code>fitcsvm</code> function documentation</a>, MATLAB specifies, what actually happens under the hood (highlighting by me):</p>\n<blockquote>\n<p>For two-class learning, <code>fitcsvm</code> <strong>assigns a box constraint to each observation</strong> in the training data.\nThe formula for the box constraint of observation <em>j</em> is</p>\n<p><em>C<sub>j</sub> = nC<sub>0</sub>w<sub>j</sub><sup></em></sup>*</p>\n<p>where <em>C<sub>0</sub></em> is the initial box constraint,\nand <em>w<sub>j</sub><sup></em></sup>* is the observation weight adjusted by Cost and Prior for observation <em>j</em>.</p>\n</blockquote>\n<p>The concept of Cost, Prior and Weight is further documented <a href="https://ch.mathworks.com/help/stats/supervised-learning-machine-learning-workflow-and-algorithms.html#mw_4cd1857b-b486-4247-b328-5fd810649696" rel="nofollow noreferrer">here</a> .When calling <code>fitcsvm</code>, you can specify a <code>Cost</code>, <code>Prior</code> and/or <code>Weights</code>:</p>\n<ul>\n<li>With a <em>Cost</em> matrix <code>C</code> (caution, also letter <code>C</code> but now used as a cost and not as the box constraint!), you can specify the cost of misclassifying an observation For <em>K</em> classes, it is a <em>K</em>-by-<em>K</em> matrix where <em>c<sub>ij</sub></em> is the cost of classifying an observation of class <em>i</em> into class <em>j</em></li>\n<li>The prior <em>p</em> is a vector containing the prior probabilities for all classes.</li>\n<li>The weight <em>w</em> allows you to specify an arbitrary weight for that observation.</li>\n</ul>\n<p>From these values, MATLAB calculates an adjusted weight <em>w<sub>j</sub><sup></em></sup>*, which is then used by <code>fitcsvm</code> as shown above to scale the Box Constraint individually for each observation. The result of this calculation is saved in the <code>BoxConstraints</code> property of the <code>ClassificationSVM</code> class. Hence, the <code>BoxConstraints</code> contains a weighted version for every observation <em>j</em> of the standard box constraint that you specified.</p>\n<p><strong>tl;dr</strong>: <code>fitcsvm</code> adjusts the scalar box constraint <code>C</code> to account for prior probabilities, misclassification costs and/or observation weights that you specify. If you use default values for these, the <code>BoxConstraints</code> will just be <code>C</code> for all values - which is exactly what you see.</p>\n"^^ . ".net"^^ . "1"^^ . "0"^^ . . . "0"^^ . . "<p>Reducing initial values <code>512</code> and <code>3125</code> to 1/10th the time cost is divided 1/3 on 1st <code>for</code> loop and 2/3 on 2nd <code>for</code> loop. Roughly 20 seconds 1st <code>for</code> loop, about 40 seconds 2nd loop.</p>\n<p>The following is not optimal, and it probably the sizes of some intermediate variables may have to changed, but the point is that <code>tic toc</code> measurements, one for each <code>for</code> loop, both fall from <code>20s</code> and <code>40s</code> down to <code>0.01s</code> each.</p>\n<p>So here you have it :</p>\n<pre><code>% k1=512;\n% k2=3125;\n\nk1=51;\nk2=312;\n\n%% to generate input_hist\ninput_hist = zeros(k1,k1,k2,'uint16');\n[xdim, ydim, binNum] = size(input_hist);\nmax_count = 5000;\n\nTC=randi([0, max_count],1,xdim*ydim);\nHV=randi([0,31], xdim*ydim, binNum);\n\ntag1=tic;\nfor x = 1:xdim\n for y = 1:ydim\n total_count = TC(x+y-1); % randi([0, max_count]);\n hist_vector = HV(x+y-1,:); % randi([0,31], 1, binNum);\n current_sum = sum(hist_vector);\n hist_vector = uint16(hist_vector * (total_count / current_sum));\n input_hist(x, y, :) = hist_vector;\n end\nend\n\nt1=toc(tag1)\n\nelementNum = sum(input_hist, 3);\nmaxElementNum = max(elementNum(:));\nminElementNum = min(elementNum(:));\n\n%% to generate values\nvalues = 4:4:12500;\nbinNum_ = length(values); % should be the same with binNum\n\n\ntag2=tic;\noutput_vals_loops = zeros(xdim* ydim, maxElementNum); % fill with 0s\nvaluesHere=[];\nelementNumHere=[];\nfor x = 1:xdim\n for y = 1:ydim\n elementNumHere = [elementNumHere elementNum(x,y)];\n % if elementNumHere &gt; 0\n % valuesHere = repelem(values, squeeze(input_hist(x,y,:)));\n % valuesHere = [valuesHere repelem(values, input_hist(x+y-1))];\n % output_vals_loops(x+y,1:elementNumHere) = valuesHere;\n % end\n end\nend\nfor x = 1:xdim\n for y = 1:ydim\n \n if elementNumHere &gt; 0\n \n valuesHere = [valuesHere repelem(values, input_hist(x+y-1))];\n \n end\n end\nend\n\nt2=toc(tag2)\n</code></pre>\n<p>Obviously these 2</p>\n<pre><code>valuesHere=[];\nelementNumHere=[];\n</code></pre>\n<p>can be improved.</p>\n<p>But the point is that <strong>the delay has gone down x1000</strong> .</p>\n<p>Also, note I have split 2nd <code>for</code> loop into 2 <code>for</code> loops.</p>\n"^^ . "1"^^ . . "<p>I'm running a MATLAB script on macOS that performs sensor fusion using GNSS and IMU data. The script runs perfectly in MATLAB R2024 but fails in MATLAB R2022 with the following error during the ECEF to ECI frame transformation:</p>\n<pre class="lang-none prettyprint-override"><code>=== Task 5: ECI and ECEF Frame Plotting ===\nError using * \nIncorrect dimensions for matrix multiplication. Check that the number of columns in the\nfirst matrix matches the number of rows in the second matrix. To operate on each element\nof the matrix individually, use TIMES (.*) for elementwise multiplication.\n\nError in untitled3&gt;transform_ecef_to_eci_gnss (line 332)\n pos_eci(i,:)= (Rz* pos_ecef(i,:).').';\n\nError in untitled3 (line 121)\n transform_ecef_to_eci_gnss(T_gnss, EARTH_ROTATION_RATE);\n</code></pre>\n<p>I suspect there might be differences between MATLAB R2022 and R2024 that affect this function. I've confirmed that all required files and dependencies are present and that the MATLAB path is set correctly in both environments.</p>\n<p>Below is the relevant portion of my code:</p>\n<pre class="lang-matlab prettyprint-override"><code>function Fusion_ECI_Corrected()\n % FUSION_ECI_CORRECTED\n % Enhanced GNSS and IMU Fusion in ECI Frame with Corrected Gravity Compensation and Drift Correction,\n % using load_nav_data().\n\n %% Task 0: Configuration\n [IMU_Data, GNSS_Data, fsIMU, fsGNSS] = load_nav_data();\n T_imu = struct2table(IMU_Data);\n T_gnss = struct2table(GNSS_Data);\n\n % Rename velocity fields if necessary\n if ismember('Velocity_X', T_gnss.Properties.VariableNames)\n T_gnss.Properties.VariableNames{'Velocity_X'} = 'VX_ECEF_mps';\n end\n if ismember('Velocity_Y', T_gnss.Properties.VariableNames)\n T_gnss.Properties.VariableNames{'Velocity_Y'} = 'VY_ECEF_mps';\n end\n if ismember('Velocity_Z', T_gnss.Properties.VariableNames)\n T_gnss.Properties.VariableNames{'Velocity_Z'} = 'VZ_ECEF_mps';\n end\n\n % Constants\n EARTH_ROTATION_RATE = 7.2921159e-5;\n % (Other constants and processing steps...)\n\n %% Task 5: ECI and ECEF Transform &amp; Plot\n fprintf('\\n=== Task 5: ECI and ECEF Transform &amp; Plot ===\\n');\n [pos_eci_gnss, vel_eci_gnss, acc_eci_gnss, ...\n pos_ecef_gnss, vel_ecef_gnss, acc_ecef_gnss] = transform_ecef_to_eci_gnss(T_gnss, EARTH_ROTATION_RATE);\n \n % (Rest of the code for storing and plotting data)\nend\n\nfunction [pos_eci, vel_eci, acc_eci, pos_ecef, vel_ecef, acc_ecef] = transform_ecef_to_eci_gnss(T_gnss, EARTH_ROTATION_RATE)\n t_rel = T_gnss.Posix_Time - T_gnss.Posix_Time(1);\n theta = -EARTH_ROTATION_RATE .* t_rel;\n cos_t = cos(theta);\n sin_t = sin(theta);\n\n pos_ecef = [T_gnss.X_ECEF_m, T_gnss.Y_ECEF_m, T_gnss.Z_ECEF_m];\n vel_ecef = [T_gnss.VX_ECEF_mps, T_gnss.VY_ECEF_mps, T_gnss.VZ_ECEF_mps];\n\n n = length(theta);\n pos_eci = zeros(n, 3);\n vel_eci = zeros(n, 3);\n for i = 1:n\n Rz = [cos_t(i), -sin_t(i), 0;\n sin_t(i), cos_t(i), 0;\n 0, 0, 1];\n pos_eci(i, :) = (Rz * pos_ecef(i, :)').';\n vel_eci(i, :) = (Rz * vel_ecef(i, :)').';\n end\n\n dt = mean(diff(T_gnss.Posix_Time));\n acc_eci = zeros(n, 3);\n acc_ecef = zeros(n, 3);\n for i = 2:n\n acc_eci(i, :) = (vel_eci(i, :) - vel_eci(i-1, :)) / dt;\n acc_ecef(i, :) = (vel_ecef(i, :) - vel_ecef(i-1, :)) / dt;\n end\n acc_eci(1, :) = acc_eci(2, :);\n acc_ecef(1, :) = acc_ecef(2, :);\nend\n</code></pre>\n<p>Here is the <strong>load_nav_data</strong> function :</p>\n<pre class="lang-matlab prettyprint-override"><code>function [IMU_Data, GNSS_Data, fsIMU, fsGNSS] = load_nav_data()\n% LOAD_NAV_DATA Loads IMU and GNSS data from files.\n%\n% [IMU_Data, GNSS_Data, fsIMU, fsGNSS] = load_nav_data()\n%\n% - IMU data is read from a .dat file (without header) and is expected to\n% have 10 columns in the order:\n% Message_Counter, Sample_Time, Gyro_X, Gyro_Y, Gyro_Z,\n% Accel_X, Accel_Y, Accel_Z, Temperature, Status.\n%\n% - GNSS data is read from a .csv file (with one header row). The file is\n% assumed to have 20 columns with the following order:\n% 1) UTC_yyyy\n% 2) UTC_MM\n% 3) UTC_dd\n% 4) UTC_HH\n% 5) UTC_mm\n% 6) UTC_ss\n% 7) Posix_Time\n% 8) Latitude_deg\n% 9) Longitude_deg\n% 10) Height_deg (stored as Height_m)\n% 11) X_ECEF_m\n% 12) Y_ECEF_m\n% 13) Z_ECEF_m\n% 14) VX_ECEF_mps -&gt; Velocity_X\n% 15) VY_ECEF_mps -&gt; Velocity_Y\n% 16) VZ_ECEF_mps -&gt; Velocity_Z\n% 17) HDOP\n% 18) VDOP\n% 19) PDOP\n% 20) TDOP\n%\n% The function also prompts for the IMU and GNSS sampling frequencies.\n%\n% Author: Your Name\n% Date: YYYY-MM-DD\n\n %% Select IMU Data File (.dat, no header)\n [imuFile, imuPath] = uigetfile('*.dat', 'Select IMU file (.dat format)');\n if isequal(imuFile, 0)\n error('No IMU file selected.');\n end\n imuFullFile = fullfile(imuPath, imuFile);\n imuRaw = readmatrix(imuFullFile);\n if size(imuRaw,2) ~= 10\n error('IMU data must have exactly 10 columns.');\n end\n % Build IMU_Data structure (each field as a 1xN row vector)\n IMU_Data.Message_Counter = imuRaw(:,1).';\n IMU_Data.Sample_Time = imuRaw(:,2).';\n IMU_Data.Gyro_X = imuRaw(:,3).';\n IMU_Data.Gyro_Y = imuRaw(:,4).';\n IMU_Data.Gyro_Z = imuRaw(:,5).';\n IMU_Data.Accel_X = imuRaw(:,6).';\n IMU_Data.Accel_Y = imuRaw(:,7).';\n IMU_Data.Accel_Z = imuRaw(:,8).';\n IMU_Data.Temperature = imuRaw(:,9).';\n IMU_Data.Status = imuRaw(:,10).';\n \n %% Select GNSS Data File (.csv)\n [gnssFile, gnssPath] = uigetfile('*.csv', 'Select GNSS file (.csv format)');\n if isequal(gnssFile, 0)\n error('No GNSS file selected.');\n end\n gnssFullFile = fullfile(gnssPath, gnssFile);\n % Read GNSS file, skipping the header row (assumes one header row)\n GNSS_raw = readmatrix(gnssFullFile, 'NumHeaderLines', 1);\n if size(GNSS_raw,2) ~= 20\n error('GNSS data must have exactly 20 columns.');\n end\n \n % Build GNSS_Data structure using fixed column indices.\n GNSS_Data.UTC_yyyy = GNSS_raw(:,1).';\n GNSS_Data.UTC_MM = GNSS_raw(:,2).';\n GNSS_Data.UTC_dd = GNSS_raw(:,3).';\n GNSS_Data.UTC_HH = GNSS_raw(:,4).';\n GNSS_Data.UTC_mm = GNSS_raw(:,5).';\n GNSS_Data.UTC_ss = GNSS_raw(:,6).';\n GNSS_Data.Posix_Time = GNSS_raw(:,7).';\n GNSS_Data.Latitude_deg = GNSS_raw(:,8).';\n GNSS_Data.Longitude_deg = GNSS_raw(:,9).';\n % Although the header is Height_deg, we store it as Height_m here.\n GNSS_Data.Height_m = GNSS_raw(:,10).';\n GNSS_Data.X_ECEF_m = GNSS_raw(:,11).';\n GNSS_Data.Y_ECEF_m = GNSS_raw(:,12).';\n GNSS_Data.Z_ECEF_m = GNSS_raw(:,13).';\n GNSS_Data.Velocity_X = GNSS_raw(:,14).';\n GNSS_Data.Velocity_Y = GNSS_raw(:,15).';\n GNSS_Data.Velocity_Z = GNSS_raw(:,16).';\n GNSS_Data.HDOP = GNSS_raw(:,17).';\n GNSS_Data.VDOP = GNSS_raw(:,18).';\n GNSS_Data.PDOP = GNSS_raw(:,19).';\n GNSS_Data.TDOP = GNSS_raw(:,20).';\n \n %% Prompt user for sampling frequencies\n prompt = {'Enter IMU Sampling Frequency (Hz):', 'Enter GNSS Sampling Frequency (Hz):'};\n answer = inputdlg(prompt, 'Sampling Frequencies', [1 50], {'400','10'});\n if isempty(answer)\n error('Sampling frequency input cancelled.');\n end\n fsIMU = str2double(answer{1});\n fsGNSS = str2double(answer{2});\n if isnan(fsIMU) || isnan(fsGNSS) || fsIMU &lt;= 0 || fsGNSS &lt;= 0\n error('Invalid sampling frequencies.');\n end\n \n %% Save sampling frequencies for future use.\n SAMPLE_FREQ = fsIMU;\n GNSS_FREQ = fsGNSS;\n save('sampling_frequencies.mat', 'SAMPLE_FREQ', 'GNSS_FREQ');\n \n disp(['IMU Sampling Frequency: ' num2str(SAMPLE_FREQ) ' Hz']);\n disp(['GNSS Sampling Frequency: ' num2str(GNSS_FREQ) ' Hz']);\nend\n</code></pre>\n<p><strong>What I've Tried:</strong></p>\n<ul>\n<li>Verified that all file paths and dependencies are correct in both MATLAB R2022 and R2024.</li>\n<li>Reviewed MATLAB’s documentation for any changes related to matrix multiplication or file I/O between versions.</li>\n</ul>\n<p><strong>My Question:</strong><br />\nHas anyone encountered similar version-specific issues with matrix multiplication in MATLAB? Are there known changes between MATLAB R2022 and R2024 that could cause this error in the <code>transform_ecef_to_eci_gnss</code> function? How can I adjust my code to ensure compatibility with the older version?</p>\n<p><strong>Additional Details:</strong></p>\n<ul>\n<li>MATLAB R2024: Works fine</li>\n<li>MATLAB R2022: Fails with the error above</li>\n<li>OS: macOS</li>\n</ul>\n"^^ . . . . "ode"^^ . . . "background"^^ . "@Cris I thought about skipping `sparse`, but I assume it's needed because OP says that looping over the nonzero entries is slow and that `L` has density 0.1%, which sounds like `L` and `C` are big matrices. As for `dot`, it adds the usual input-checking overhead and then does the same as my last line. Except it also has an unwanted conjugate :-)"^^ . "0"^^ . . . . "0"^^ . . . . . . . . . "<p>I need to make a table that has column names &quot;Radii&quot;, &quot;SurfaceA&quot;, and &quot;Volume&quot;. But when I display the table it names the columns &quot;Var1&quot;, &quot;Var2&quot;, and &quot;Var3&quot;. What is causing this?</p>\n<p>Im also brand new to Matlab, if there's some easy way to optimize this please let me know.</p>\n<pre class="lang-matlab prettyprint-override"><code>Radii = [0.050:0.050:0.300];\nSurfaceA = [];\nVolume = [];\nfor i = 1:length(Radii)\n SurfaceA(i) = 4*pi*Radii(i)^2;\n Volume(i) = (4*pi*Radii(i)^3)/3;\nend\nSphere = table(Radii',SurfaceA',Volume');\ndisp(&quot;#1&quot;)\ndisp(&quot;Sphere = &quot;)\nfprintf(&quot;\\n&quot;)\ndisp(Sphere)\n</code></pre>\n<p>This returns</p>\n<pre class="lang-none prettyprint-override"><code>#1\nSphere = \n\n Var1 Var2 Var3 \n ____ ________ _________\n\n 0.05 0.031416 0.0005236\n 0.1 0.12566 0.0041888\n 0.15 0.28274 0.014137\n 0.2 0.50265 0.03351\n 0.25 0.7854 0.06545\n 0.3 1.131 0.1131\n</code></pre>\n<p>Should be</p>\n<pre class="lang-none prettyprint-override"><code>#1\nSphere = \n\n Radii Surface A Volume \n ____ ________ _________\n\n 0.05 0.031416 0.0005236\n 0.1 0.12566 0.0041888\n 0.15 0.28274 0.014137\n 0.2 0.50265 0.03351\n 0.25 0.7854 0.06545\n 0.3 1.131 0.1131\n</code></pre>\n"^^ . . "0"^^ . "<p>The distance between a point and a plane will be the length of a line normal to the plane which intersects the point. Given that, this question has three distinct parts, as I see it.</p>\n<ol>\n<li>Create a plane based on 3 clustered points</li>\n<li>Calculate lines normal to that plane which also go through specified points</li>\n<li>Get the length of those lines between the points and plane intersections</li>\n<li>Plotting</li>\n</ol>\n<hr />\n<p>A great resource for this problem can be found <a href="https://math.umd.edu/%7Ejmr/241/lines_planes.html" rel="nofollow noreferrer">here</a>. Aspects of this answer are modified snippets from that article, and I recommend giving it a read.</p>\n<p>The function you used is well suited for plotting plane meshes. The normal calculation, as you included, is also very useful. However, since we need to calculate intersection points on the plane, having a function version of the plane is helpful. To do this, I have used <a href="https://www.mathworks.com/help/symbolic/syms.html" rel="nofollow noreferrer">scalar symbolic vars</a> and <a href="https://www.mathworks.com/help/symbolic/symbolic-variables-expressions-and-functions.html?s_tid=CRUX_lftnav" rel="nofollow noreferrer">functions</a>.</p>\n<pre class="lang-matlab prettyprint-override"><code>function [normal, planefunction, solvedplanefunction, P] = generate_plane(p1, p2, p3)\n normal = cross(p1 - p2, p1 - p3); % get the normal\n \n syms x y z\n P = [x, y, z];\n planefunction = dot(normal, P - p1); % define a function version of the plane\n solvedplanefunction = solve(planefunction, z); % solve this function for z (used later)\nend\n</code></pre>\n<p>The next step is to calculate the lines normal to the plane which intersect given points. Since we have the equation for the plane, and a version of it solved for z, this is pretty straightforward. First, we need to create a line that starts at our point, and has the same normal as our plane. Then we just need to solve for when that line's equation is equal to our plane's equation.</p>\n<pre class="lang-matlab prettyprint-override"><code>function [closest_point] = generate_closest_planar_point(normal, planefunction, P, point)\n syms t\n line = point + t*normal; % create line equation\n \n tempfunction = subs(planefunction, P, line);\n t0 = solve(tempfunction); % get value of t where the equations are equal\n closest_point = subs(line,t,t0); % plug in t0 to line equation to get point\nend\n</code></pre>\n<p>With that, most of our problem is solved. Essentially, we need to calculate the norm of each of our calculated line segments, and plot the planes and line segments. So, setting the problem up with arbitrary points that comprise objects m and n:</p>\n<pre><code>% defining the objects\nObjectM_A = [1 1 1];\nObjectM_B = [2 0 2];\nObjectM_C = [1 3 3];\n\nObjectN_A = [3 3 3];\nObjectN_B = [2 2 9];\nObjectN_C = [1 4 2];\n\n% creating the plane for m\nfigure()\n[normalM, planeM, solvedplaneM, PM] = generate_plane(ObjectM_A, ObjectM_B, ObjectM_C);\nfsurf(solvedplaneM, [-5 5 -5 5]), hold on % plot the mesh by its function\n\n% creating the plane for n\n[normalN, planeN, solvedplaneN, PN] = generate_plane(ObjectN_A, ObjectN_B, ObjectN_C);\nfsurf(solvedplaneN, [-5 5 -5 5])\n\n% for each pt in m, find the closest point on n\n% print the distance\nfor pt = {ObjectM_A, ObjectM_B, ObjectM_C}\n cur = pt{1};\n cur_closest = double(generate_closest_planar_point(normalN, planeN, PN, cur));\n plot3([cur_closest(1) cur(1)], [cur_closest(2) cur(2)], [cur_closest(3) cur(3)], 'r','LineWidth', 2); hold on\n \n fprintf(strcat(&quot;Object M, point: [&quot;, num2str(cur), &quot;] -&gt; [&quot;, num2str(cur_closest), &quot;](length = &quot;, string(norm(cur-cur_closest)),&quot;)\\n&quot;))\nend\n\n% for each pt in n, find the closest point on m\n% print the distance\nfor pt = {ObjectN_A, ObjectN_B, ObjectN_C}\n cur = pt{1};\n cur_closest = double(generate_closest_planar_point(normalM, planeM, PM, cur));\n plot3([cur_closest(1) cur(1)], [cur_closest(2) cur(2)], [cur_closest(3) cur(3)], 'b','LineWidth', 2); hold on\n \n fprintf(strcat(&quot;Object N, point: [&quot;, num2str(cur), &quot;] -&gt; [&quot;, num2str(cur_closest), &quot;](length = &quot;, string(norm(cur-cur_closest)),&quot;)\\n&quot;))\nend\n\n% plotting points\nplot3(ObjectM_A(1),ObjectM_A(2),ObjectM_A(3),'r.','Markersize',25)\nplot3(ObjectM_B(1),ObjectM_B(2),ObjectM_B(3),'r.','Markersize',25)\nplot3(ObjectM_C(1),ObjectM_C(2),ObjectM_C(3),'r.','Markersize',25)\nplot3(ObjectN_A(1),ObjectN_A(2),ObjectN_A(3),'b.','Markersize',25)\nplot3(ObjectN_B(1),ObjectN_B(2),ObjectN_B(3),'b.','Markersize',25)\nplot3(ObjectN_C(1),ObjectN_C(2),ObjectN_C(3),'b.','Markersize',25)\n\nzlim([-5 5]);\n\n</code></pre>\n"^^ . . "0"^^ . "If there’s a difference, it most likely is in the exact weights used for red, green and blue."^^ . . . . . . . "<p>So I'm looking to create a custom RL agent in matlab where the environment is provided by a Simulink model.</p>\n<p>Before I was using Matlab built in rlDDPGAgent object as my agent and then use the train(agent, env) built in function to perform my training where agent = rlDDPGAgent object and env = rlSimulinkenv object. Then the train() built in function does the simulation loop for me internally.</p>\n<p>But now since I'm creating a custom Agent, I'm assuming I can't use train() built in function anymore. Would I have to just create my own training loop in matlab script?\nAnd how would I get feed my actions into my Simulink environment and acquire the next state? I'm not looking for line by line code by just a general direction/format I can follow to start.</p>\n<p>Thanks</p>\n"^^ . . "1"^^ . . . . "Help me understand your question better. So, you have 2 3-point clusters(the two clusters you listed are identical, which I assume is an error). Are you asking for the distance between the planes created by each cluster? If so, note that this is only applicable when the planes are parallel, because the distance between planes is non-constant. Or, are you trying to find the distance that points in the other cluster are from the plane? If so, do you want all of the points or just a specific one? I ask because you use `X` in your final, `dot()` call, but that is not defined anywhere."^^ . . "matrix-multiplication"^^ . . . . . . . . . . . . . . "<p>You directly have an example in the <a href="https://www.mathworks.com/help/symbolic/dsolve.html" rel="nofollow noreferrer">documentation</a> of a second order equation with initial conditions on the unknown function and its derivative.</p>\n<p>Applying it to your problem gives:</p>\n<pre><code>syms i(t) R L C V0 \n\n% Define component values\nR = 10;\nL = 1;\nC = 1;\nV0 = 12;\n\n% Define the differential equation\neqn = L*diff(i, t, 2) + R*diff(i, t) + (1/C)*i == 0;\n\n% Define initial conditions\nDi = diff(i,t);\ninit_cond = [i(0)==0, Di(0)==V0/L];\n\n% Solve the differential equation with initial conditions\niSol(t) = dsolve(eqn, init_cond);\n\n% Display the particular solution\ndisp('Particular Solution for i(t):')\ndisp(iSol(t))\n</code></pre>\n<p>Edit: I have called the unknown <code>i</code>, like you did, but it is good practice not to use <code>i</code> (or <code>j</code>) as variable names in Matlab.</p>\n<p>Edit 2: It seems like the variable in the differential equation governing the behavior of a RLC circuit should be the charge <code>q</code> instead of the current <code>i</code>. Nonetheless the equation is right (if solving for the charge)</p>\n"^^ . "How to use low-frequency filtering to process the rising signal"^^ . "How to solve this error using "trainNetwork" on Matlab"^^ . "gradcam"^^ . . "0"^^ . "1"^^ . . . . "0"^^ . . "1"^^ . . "@Millemila You can edit the [startup script](https://www.mathworks.com/help/matlab/ref/startup.html) or just have a standard (standalone) function/script which you run before running any other relevant code - maybe you have a file you already run before you start working which sorts out your paths etc where you could include it. This does not need editing into all of your other code, you just run it once before other stuff."^^ . . . "Thank you. Can you please discuss a way to have it done without changing all codes? Please show what "on startup" means. Where is the startup file? what should i write in there?"^^ . . "1"^^ . "<p>My strain time-domain data shown in figure 1 contains significant high-frequency noise. The segment I focus on is the strain rising phase shown in figure 2, where the amplitude can be truncated at 1e4. When applying FFT-based low-frequency filtering, I found that the selected time duration of the filtering region significantly affects the filtering results. How should I resolve this issue?</p>\n<p><a href="https://i.sstatic.net/87D0I9TK.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/87D0I9TK.jpg" alt="enter image description here" title="figure 1" /></a></p>\n<p><a href="https://i.sstatic.net/gwzOReMI.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gwzOReMI.jpg" alt="enter image description here" /></a></p>\n<p><a href="https://drive.google.com/file/d/1WNoSqao_q1bHrdLoxRK7cPm3CoxljuWt/view?usp=drive_link" rel="nofollow noreferrer">signal-data</a></p>\n<pre><code>clc;clear;close all;\n%% load data\nload('20250310signal1.mat');\nt=ttt';\ny=yyy';\n%% \nfs = fix(1/(t(2)-t(1))); \nn = length(y); \nY = fft(y); \nf = (0:n-1)*(fs/n); \n%% Low-pass filtering (retain DC and low-frequency components)\ncutoff = 12500; % cut-off frequency\nY_filtered = Y; \nY_filtered(f &gt; cutoff) = 0; \n%% Inverse FFT to obtain filtered signal\ny_filtered = ifft(Y_filtered, 'symmetric'); \n%% Plot results\nfigure;\nplot(t, y);hold on;\nplot(t, y_filtered);\nxlabel('Time (s)');\nylabel('Amplitude');\nlegend('data','filtered data')\n</code></pre>\n"^^ . . "<p><code>repelem</code> can be used once to compute the histogram. All other operations are needed for placing the input arrays in the correct order:</p>\n<pre><code>output_values = zeros(maxElementNum, xdim, ydim);\nvals = repmat(reshape(values, [], 1), xdim * ydim, 1);\nmask = reshape(elementNum, 1, xdim, ydim) &gt;= (1:maxElementNum).';\noutput_values(mask) = repelem(vals, reshape(permute(input_hist, [3, 1, 2]), [], 1));\noutput_values = ipermute(output_values, [3, 1, 2]);\n</code></pre>\n"^^ . . . . . "<p>I have been trying to solve this issue with out any luck so far.</p>\n<p>From the Coursera course &quot;Introduction to Data, Signal, and Image Analysis with MATLAB&quot; the below code is retrieved. I'm trying to see if I can get this working in Octave 9.2. But that result in the error:</p>\n<p>error: contourc: X, Y, and Z must be real numeric matrices error: called from contourc at line 110 column 5 contour at line 146 column 14 contour at line 80 column 18 classification1 at line 19 column 3</p>\n<p>The class of X, Y and cls is double and the size of all 3 is 4x8.</p>\n<p>Reading this post: Octave Contour plots The contour function works fine. No error. But with the code:</p>\n<pre><code>function classification1()\n load fisheriris\n pkg load statistics\n [~,~,s] = unique(species);\n figure(1);\n plot(meas(s==1 ,1), meas(s==1, 2), 'rx')\n hold on\n plot(meas(s==2 ,1), meas(s==2, 2), 'go')\n plot(meas(s==3 ,1), meas(s==3, 2), 'b*')\n xlabel('Feature 1');\n ylabel('Feature 2');\n legend('setosa', 'versicolor', 'virginica');\n [X,Y] = meshgrid(4:.01:8, 2:.01:4.5);\n cls = my_iris_classifier([X(:), Y(:)]);\n cls = reshape(cls, size(X));\n contour(X, Y, cls==1,[1,1], 'r--');\n contour(X, Y, cls==2, [1, 1], 'g--');\n contour(X, Y, cls==3, [1, 1], 'b--');\n\nendfunction\n\nfunction class = my_iris_classifier(feat)\n class = zeros(size(feat,1),1);\n for i = 1:size(feat,1);\n if feat(i,1) &gt; 6\n class(i) = 3;\n elseif feat(i,2) &gt; 3\n class(i) = 1;\n else\n class(i) = 2;\n endif\n endfor\n\nendfunction\n</code></pre>\n<p>it doesn't.</p>\n"^^ . . "How to get 'Live Editor Evaluation Helper' .m file name from live script through another live script?"^^ . . "0"^^ . . "<p>I am using code using the trainNetwork function with MATLAB to train and predict some data, however I am getting this error message &quot;Invalid training data. Y must be a vector of categorical responses.&quot;\nI am using some training Data and validation data for a system with 4 inputs and 1 output and I want to train my model.\nDATA sizes are:\n<strong>Training DATA&gt;&gt;</strong>\nTraining inputs data of the size: (1973, 4),\nTraining output data of the size: (1973, 1).</p>\n<p><strong>Validation DATA&gt;&gt;</strong>\nValidation inputs data of the size: (120, 4), validation output data of the size:(120, 1)</p>\n<p>I tried to change the size of DATA, transposed them and convert them to categorical form, but I am getting a second message error which is:\n&quot;Number of observations in X and Y disagree&quot;</p>\n<p>Code used:</p>\n<pre><code>XTrain=Input_Train\nYTrain=Output_train\nXValidation=Input_val\nYValidation=Output_val\n\nlayers = [\n imageInputLayer([28 28 1])\n convolution2dLayer(3,8,'Padding','same')\n batchNormalizationLayer\n reluLayer \n maxPooling2dLayer(2,'Stride',2)\n convolution2dLayer(3,16,'Padding','same')\n batchNormalizationLayer\n reluLayer\n maxPooling2dLayer(2,'Stride',2)\n convolution2dLayer(3,32,'Padding','same')\n batchNormalizationLayer\n reluLayer \n fullyConnectedLayer(10)\n softmaxLayer\n classificationLayer];\noptions = trainingOptions('sgdm', ...\n 'MaxEpochs',8, ...\n 'ValidationData',{XValidation,YValidation}, ...\n 'ValidationFrequency',200, ...\n 'Verbose',false, ...\n 'Plots','training-progress');\n net = trainNetwork(XTrain,YTrain,layers,options)\n</code></pre>\n"^^ . . "1"^^ . "0"^^ . . . "0"^^ . . . . "1"^^ . . "0"^^ . . . "4"^^ . . "0"^^ . . . . . "If you apply low-pass filtering to remove high-frequency noise, that is also going to soften the sharp rise, because the rise is composed of high frequencies. I don't think you can avoid that if you use (linear, time-invariant) filtering. However, your plot suggests there may be some other issue, because there is a very slow increase on the left but the right part is horizontal with a very sharp upper corner. Please post a minimum working example"^^ . . . . . . . "Thanks all. So far `min` is the fastest. I have [tested](https://gist.github.com/magnesium2400/48b70aa3291e07f24e8cffffbf627bfc) on 1000*1000 sparse logical matrices but will actually end up using matrices up to 30k*30k."^^ . "Have you considered to check whether your shift works like intended by inspecting the spectrum before and after shifting ?"^^ . . . . . . . "0"^^ . . . "2"^^ . "frequency"^^ . . . . "Run MATLAB cells in Visual Studio code"^^ . "0"^^ . . . . . . "0"^^ . "0"^^ . "4"^^ . "0"^^ . . "2"^^ . "2"^^ . "For loop inside While loop not breaking - Matlab"^^ . . . . . . . . . . "Please reread the tag descriptions that you picked. The tag [tag:STL] is not suitable to your question."^^ . "nice to know... but it sounds anyway pointless since I'm compiling a DLL not an exe"^^ . . . . . "<p><code>mfilename</code> returns the path of the script. When you compile MATLAB code with MATLAB Compiler, it creates a CTF file, which is in essence just a ZIP file bundling all M-files and data files together. When this “executable” is run, this CTF file is unpacked into a temporary directory, the scripts are run from there. So this is the <code>mfilename</code> you see.</p>\n<p>In code bundled into a CTF file, you can use <a href="https://www.mathworks.com/help/compiler/ctfroot.html" rel="nofollow noreferrer"><code>cftroot</code></a> to get the directory where the CTF file is unpacked. This is the root for all the files while the program is running.</p>\n<p>There doesn’t seem to be a way to find the directory where the CTF itself is.</p>\n<p>Note that <code>pwd</code> shows the working directory, which can be set by the user when launching a program, and can be changed by the program. Do not depend on it to find the CTF file.</p>\n<p>It sounds like your are deploying the CTF file together with data files, and you want to locate these data files. Instead of putting those next to the CTF file, put them inside. You can use the <code>-a</code> option to the <code>mcc</code> command to include any file or directory into the CTF file, see <a href="https://www.mathworks.com/help/compiler/mcc.html#mw_1a52a1c0-e230-4e98-be45-fad5d458fdec" rel="nofollow noreferrer">here</a>.</p>\n"^^ . . . "1"^^ . "0"^^ . . "1"^^ . "0"^^ . . "0"^^ . . . "Wolfie (Bill's comment from proving ground), pt 1: v can be very small to very big, e.g. anywhere from 20 to 20000. m and n also have very wide ranges, either one can be between 400 to 200,000. Assuming max values for m and n are 200,000, that means L can be at most a 40 billion entry sparse matrix. Additionally, the larger these L matrices are, the fewer the percentage of entries in it that are nonzero (e.g. in the max case of 40 billion entries, I'd assume that less than 1e-5 % or the entries of L are nonzero (400,000)."^^ . . . . "thanks for your clarification. I assumed that referrring to the pointers would be sufficient, but agree, I could formulate more clear, with a simple code example."^^ . . "Regarding difference between event and callback I suspect somehow like this is happening in matlab arcanes: Mouse is moved > HitTest cache is reset > Event `WindowMouseMotion` is fired > HitTest cache is updated > `WindowButtonMotionFcn` callback is called"^^ . . "while-loop"^^ . . . . . . . . . . "0"^^ . "1"^^ . "2"^^ . . "3"^^ . . "simulink"^^ . "1"^^ . . . "1"^^ . . . . "<h2>Preamble</h2>\n<p>Some time ago, I created an application in matlab where I could move/rotate some object directly from the mouse (i.e. some kind of mini-cadtool interface):</p>\n<p><a href="https://i.sstatic.net/UCGpJvED.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UCGpJvED.gif" alt="MiniCadInMatlab" /></a></p>\n<p>I created the application on the go and was directly attaching to <a href="https://fr.mathworks.com/help/matlab/ref/matlab.ui.figure-properties.html#buiwuyk-1-WindowButtonMotionFcn" rel="nofollow noreferrer"><code>WindowButtonMotionFcn</code></a> callback in <code>figure</code> properties and using the undocumented <a href="https://undocumentedmatlab.com/articles/undocumented-mouse-pointer-functions" rel="nofollow noreferrer"><code>hittest</code></a> function to detect objects below the mouse and everything was fine ...</p>\n<p>Now I would like to rework this code to extract cad-manipulation part to some sort of <code>uicad</code> object just like we can have <code>uicontrol</code>, <code>uipanel</code>, etc... so I can use it as component on the shelf and plug it in any figure I want.</p>\n<p>Especially I wanted not to directly modify <code>WindowButtonMotionFcn</code> of the parent figure ... Indeed, if I want to do something modular, I cannot guarantee that this callback is not already in use (or will be in use) by someone else.</p>\n<p>I then figured out that I could use equivalent <code>WindowMouseMotion</code> event in <code>figure</code> object so this way it is possible to attach as many event listeners as we want (see <a href="https://fr.mathworks.com/help/matlab/ref/handle.addlistener.html" rel="nofollow noreferrer"><code>addlistener</code></a>) without disturbing other listeners or even disturbing the <code>WindowButtonMotionFcn</code> property itself (which support only one listener).</p>\n<h2>Problem</h2>\n<p>Unfortunately when using <code>event</code> instead of <code>callback</code> (which obviously should be the same), <code>hittest</code> function no longer work as espected and no longer return the object which is below the mouse. Below code illustrate the issue:</p>\n<pre><code>function [] = TestFigEvents()\n%[\n % Create figure\n fig = figure(666); \n clf(fig, 'reset'); \n fig.Color = 'black';\n\n % Add axes\n ax = axes(); \n daspect(ax, [1 1 1]); \n ax.Visible = 'off';\n ax.Clipping = 'off';\n view(ax, -45, 30);\n\n % Add something\n s = surface(ax, 160*membrane(1,100));\n s.EdgeColor = 'none';\n\n % Different way to attach to mouse move event\n if (true)\n fig.WindowButtonMotionFcn = @onMouseMove;\n else\n addlistener(fig, 'WindowMouseMotion', @onMouseMove);\n end\n%]\nend\nfunction [] = onMouseMove(s, e)\n%[\n ht = hittest(s); % Will only detect correct object if using 'WindowButtonMotionFcn'\n disp(ht); \n%]\nend\n</code></pre>\n<p>When going through <code>WindowButtonMotionFcn</code>, the <code>hittest</code> function indeed return the correct <code>surface</code> object when the mouse is over it. But when going through <code>WindowMouseMotion</code> event it is always returning the <code>figure</code> object only.</p>\n<h2>Question</h2>\n<p>Well I guess nobody outside Mathworks staff can help me solving for undocumented <code>hittest</code> not working when using <code>events</code> instead of <code>callbacks</code>, anyway:</p>\n<ul>\n<li>Is there another <strong>fast</strong> way I can detect objects below the mouse pointer rather than using <code>hittest</code> ?</li>\n<li>Is there a way I can attach to <code>WindowButtonMotionFcn</code> callback even if some callback is already defined for it ?</li>\n<li>Maybe there already exist some sort of <code>uicad</code> toolbox that I could use to move/rotate object easily from the mouse (paying toolbox is ok) ?</li>\n</ul>\n<h2>edit</h2>\n<p>I tested both with R2022b and R2024b ... and also both with <code>figure</code> and <code>uifigure</code> ... Here below is test code with <code>uifigure</code>:</p>\n<pre><code>function [] = TestUiFigEvents()\n%[\n % Create figure\n fig = uifigure(); \n fig.Color = 'black';\n\n % Add axes\n ax = uiaxes(fig); \n daspect(ax, [1 1 1]); \n ax.Visible = 'off';\n ax.Clipping = 'off';\n view(ax, -45, 30);\n\n % Add something\n s = surface(ax, 160*membrane(1,100));\n s.EdgeColor = 'none';\n\n % Different way to attach to mouse move event\n if (false)\n fig.WindowButtonMotionFcn = @onMouseMove;\n else\n addlistener(fig, 'WindowMouseMotion', @onMouseMove);\n end\n%]\nend\nfunction [] = onMouseMove(s, e)\n%[\n ht = hittest(e.Source); % Will only detect correct object if using 'WindowButtonMotionFcn'\n disp(ht); \n%]\nend\n</code></pre>\n"^^ . . . . "I also tried to specify the .net framework 4.8 in mcc line.. nothing changes."^^ . . . . "2"^^ . "1"^^ . . "<p>When on remote desktop, for all my colleagues and myself, matlab creates a figure that is for half outside of the screen and we cant see it until you enlarge it. Is there a permanent fix that doesnt require changing updating all our hundreds matlab scripts? If not, what are the best lines of code to have this working in general (remotely or locally) It doesnt happen if we open it locally.</p>\n"^^ . . "mfilename not predictable value return for compiled code"^^ . . . . . . . . . . . ""matlab -nodesktop -nosplash -r `"run('model.m'); exit;`"""^^ . . . . "1"^^ . . . . . "0"^^ . . . . . . . . "<p>Appended a 3rd way to catch zeros with <code>while</code> loops, <strong>reducing x10 time required.</strong></p>\n<pre><code>x = sparse(5000,1); % Create sparse array [10% filled]\nx(randsample(5000,500)) = 1;\nnRuns = 1e5; \n\nidx = zeros(nRuns,1); % Find first element, a million times\ntag1=tic;\nfor n=1:nRuns\n idx(n) = find(x==0,1);\nend\nt1=toc(tag1)\n\n\n%%\n% x = sparse(5000,1); % Create a sparse array [10% filled]\n% x(randsample(5000,500)) = 1;\n% nRuns = 1e5; \n\nidx = zeros(nRuns,1); % Find the first element, a million times\ntag2=tic;\nfor n=1:nRuns\n for kk = 1:numel(x)\n [ii,jj] = ind2sub(size(x), kk);\n if x(ii,jj)==0; \n idx(n) = ii + (jj-1)*n; \n break; \n end\n end\nend\nt2=toc(tag2)\n\n%%\n\ntag3=tic;\nidx=[];\nnx_max=prod(size(x));\nnx=1;\nwhile nx&lt;nx_max\nwhile ~x(nx) \n nx=nx+1;\n idx=[idx nx];\n if nx&gt;=nx_max\n break;\n end\nend\n\nnx=nx+1;\nend\n\nt3=toc(tag3)\n</code></pre>\n<p>resulting :</p>\n<pre><code>t1 =\n 0.563633000000000\nt2 =\n 0.420241800000000\nt3 =\n 0.017343400000000\n</code></pre>\n<p>To compare delays there's no need to generate a different sparse matrix <code>x</code> for each case, on the contrary, using the same matrix <code>x</code> one makes sure that the comparison is correct because it's on exactly the same matrix.</p>\n"^^ . "Wolfie (Bill's comment from proving ground), pt 2: "It will be hard to beat A * B. If you compute C = A * B you can index the values you seek with D = C(L) if L is logical, or D=C(logical(L)) if L is numeric containing 0s and 1s" I could not get D=C(L) to work for logical L as I received the error "Array indices must be positive integers or logical values." I think they mean D=C(find(L)) instead of D=(C(L)) which errors out. I tested and D=C(find(L)) is slower. (A * B) takes 18.8 sec, (A * B) .*L takes 28.5 sec, and D=C(find(L)) takes about 92 seconds."^^ . "<p>I fixed the problem simply removing:</p>\n<pre><code>CMDLINE250=&quot;mt -outputresource:$EXE';'2 -manifest $MANIFEST&quot;\n</code></pre>\n<p>I don't know why this option have been added to the command line (it's a reccomendation provided by MatLab support) but it deals with a manifest that's not available following the standard workflow for creating the library.\nRemoving it just let the process and gracefully and the DLL file is finally created.</p>\n"^^ . "1"^^ . . . . . . . "Because a `while` loop only checks its guard at the start of each iteration."^^ . . . . . . . "0"^^ . . . . "database"^^ . "0"^^ . . "0"^^ . . . "1"^^ . . "1"^^ . . "0"^^ . . "0"^^ . . . "Sparse arrays store non-zero elements in order. Just look through those until you find a missing element."^^ . . . . "satellite"^^ . . "0"^^ . "3"^^ . . "How to create a CCS ToolchainInfo object in Matlab2023?"^^ . "0"^^ . "components"^^ . "But I was thinking of looking through the data as stored: a sparse matrix stores indices to non-zero elements and their values. You should be able to iterate faster over just the indices of the non-zero elements. Except I don’t know how to get that data in MATLAB. In a MEX-file this would be simple: https://www.mathworks.com/help/matlab/apiref/mxgetir.html — indexing into a sparse array is more expensive than indexing into a full array."^^ . "<p>I have two STL files of medical data.</p>\n<p>The <a href="https://www.mathworks.com/help/medical-imaging/ug/get-started-with-medical-registration-estimator.html" rel="nofollow noreferrer">Medical Registration Estimator app</a> does not accept this format.</p>\n<p>How can I do registration of this two surfaces?</p>\n<p>Thanks!</p>\n<p>I tried using the registration estimator after saving the triplot images of the stl files.</p>\n<p>I tried ICP but the clouds are visualy not registered, far from each other:</p>\n<pre><code>%Align Two Point Clouds Using Plane-to-Plane ICP Registration\n\n%reference\nreference_data = stlread('ref.stl');\nreference_points = reference_data.Points;\nptCloud = pointCloud(reference_points(:,:,:));\npcshow(ptCloud)\n\n\n%moving\nmoving_data = stlread('moving.stl');\nmoving_data_points = moving_data.Points;\nmoving_ptCloud = pointCloud(moving_data_points(:,:,:));\npcshow(moving_ptCloud)\n\n%Register two point clouds\ntform = pcregistericp(moving_ptCloud,reference_ptCloud);\n\nfigure\npcshowpair(moving_ptCloud,reference_ptCloud,VerticalAxis=&quot;Y&quot;,VerticalAxisDir=&quot;Down&quot;)`\n</code></pre>\n<p>How can I improve it?</p>\n<p>Thanks!</p>\n"^^ . "1"^^ . "0"^^ . . "0"^^ . . . . "0"^^ . "The C++ standard library has the Mersenne Twister algorithm. But there are two things you need to replicate from `rand`: the random number generator (which generates integers), and the conversion to the 0-1 range. This last step has multiple possible implementations as well, you’ll have to figure out how MATLAB does it."^^ . "0"^^ . "0"^^ . "variable-assignment"^^ . "R & MATLAB integration in Windows 10"^^ . "0"^^ . "1"^^ . "0"^^ . . . "So you are trying to generate an array that has the values described by the histogram? That is curious, what do you need it for? Note that your output might have more zeros than described by the histogram."^^ . . "0"^^ . "1"^^ . "0"^^ . . . "@chtz If `A` and `B` can be reordered so that the result can be obtained with (sub-)matrix multiplication, I think that can save time and is worth a separate answer. I fail to see how to do that"^^ . "1"^^ . . "<p>One can easily concatenate (stack up) four arrays by using:</p>\n<pre><code>B = cat(3, A, A, A, A); % here A is 2-dimensional M x N matrix and B is 3-dimensional M x N x 4 stack\n</code></pre>\n<p>How is it possible to concatenate (stack) <code>n</code> arrays to get <code>M x N x ... x n</code> array? The dimenisonality of <code>A</code> array is known (or easy to figure as <code>numel(size(A))</code>)</p>\n<pre><code>B = A; % A is M x N 2-dimensional array here\nfor ii = 1 : n-1\n B = cat(3, B, A);\nend\n</code></pre>\n<p>is very poor,</p>\n<pre><code>B = nan([size(A),n]);\nfor ii = 1 : n\n B(:, :, ii) = A;\nend\n</code></pre>\n<p>is quite slow too.</p>\n<p>The motivation is to find the array in <code>S</code>-stack that is closest to the array <code>A</code>.</p>\n<p>If I want to find element of vector <code>S</code> closest to a scalar <code>a</code> it is super simple:</p>\n<pre><code>distances = abs(S - a);\nFOO = find(distances == min(distances),1);\n</code></pre>\n<p>but this opperation <code>S - a</code> works only for arrays of same size or when <code>a</code> is a scalar.</p>\n<p>In more general manner I want to perform a dot-opperation on <code>B</code> and <code>A</code>, like <code>B.*A</code>, <code>B./A</code>, etc.</p>\n"^^ . "<p>I have created a shallow fully connected NN that has an input layer, 1 hidden layer and an output layer. I want to set some of the weights of the hidden layer with specific values and freeze them so that the values don't change during training. I have noticed that in MATLAB it is possible to freeze a particular layer but I don't see any solutions that are related to specific weights. Can someone guide me on how to get started with it? Thanks!</p>\n"^^ . . "After that if you think that the performance isn't satisfying you can implementing a parallel version of `repelem` in a c/c++ mex function that."^^ . "2"^^ . "1"^^ . . . . . "to magnesium, chtz, and Louis, pt 2: I indeed found it faster: for the dimensions of the data I used, (A * B) too 18.8 sec, (A * B) .* L took 28.5 sec, and my "blocklooping" solution above took about 7.0 sec. But I should also note, in the thread on reddit (https://www.reddit.com/r/matlab/comments/1iro2m4/need_to_vectorize_efficiently_calculating_only/mdfs8l3/?context=3), a user "86billionfireflies" provided a vectorized solution that was faster than my "blocklooping" solution: 86's solution took 5.4 sec."^^ . "1"^^ . "0"^^ . "0"^^ . "Use `break` or `return` to exit the `for` loop early."^^ . . "0"^^ . "0"^^ . . . "The values in the 1st column are not deleted, there just are not enough decimal places to print both `-1.3275e-17` and `-0.2168`, so the first column just shows `-0.0000`. If you display `A(1,1)`, you'll see that the correct value is still there."^^ . . . . "1"^^ . "1"^^ . "Performance Issues with EIGEN vs Matlab with elementwise operations"^^ . . "1"^^ . "What is `load_nav_data()`? Did you check that it produces the same output in both versions? It is likely that the two MATLABs have different files on their paths, and thus both could be running a different version of some function you depend on. MATLAB itself is unlikely to have changes that cause something to work in one version and not another. If you depended on new functionality not yet present in your 2022 version, you should be getting an error in that version."^^ . . . . . . "5"^^ . . . "Note that `tic/toc` is not recommended for accurate timings for a multitude of reasons. Use [`timeit()`](https://www.mathworks.com/help/matlab/ref/timeit.html) instead. This circumvents several problems, mainly the start-up time of the engine and averaging out differences in run time between runs."^^ . "vector"^^ . . . . . "0"^^ . "Please provide a title that actually summarizes your question or problem."^^ . "1"^^ . . "for-loop"^^ . "0"^^ . . . "<p>I'm having trouble understanding what Matlab does regarding the <code>lsim</code> function.<br />\nAs far as I know, if I give Matlab a continuous-time transfer function and a sampled input and vector time, I normally discretizes the transfer function by using a zero-order hold or a first-order hold (<code>ZOH</code> or <code>FOH</code>).</p>\n<p>However, when I try to compare directly using <code>lsim</code>, and using <code>lsim</code> on both discretized models, I don't get matching results, neither for <code>y_zoh</code> or <code>y_foh</code> (none of them are identical to <code>y_cont</code>).</p>\n<p>I used this small code to try to understand the function better:</p>\n<pre><code>Ts=0.1; %sampling time\nt=0:Ts:10; %time vector\nu=cos(t); %input signal\n\nG=tf(1,[1 1]); %Continuous-time model\ny_cont=lsim(G,u,t); %Output of the continuous-time model\n\nGzoh=c2d(G,Ts,'zoh');%ZOH discretization\ny_zoh=lsim(Gzoh,u);\n\nGfoh=c2d(G,Ts,'foh');%FOH discretization\ny_foh=lsim(Gfoh,u,t);\n</code></pre>\n<p><strong>Question:</strong><br />\nCould somebody explain what is Matlab doing differently regarding the computation of <code>y_cont</code> with respect to <code>y_foh</code> (as the input is a cosine, normally Matlab should use a <code>FOH</code>)?</p>\n"^^ . . "0"^^ . . . "2"^^ . "0"^^ . . . "0"^^ . . . . . . . "Thank you, Rahnema1! I've tried your solution and it is ~2X faster at the cost of 25GB memory on my dataset. It is very clever and insightful. I'm just thinking is there a better way of doing this conversion? Because from my rough understanding it is nothing more than a lot of copies of values, is it?\nI've also edited my question and provide my data as well as your solution. Thank you again for your insights and help!"^^ . . "Sorry Luis I was not specific, I only need to compute the nonzero entries of C as a vector."^^ . . "I dont want to be the arse, but you are quoting directly from their homepage. Without proper attribution this is a form of plagiarism. Why not add a link to the question? I will do that for you...."^^ . . . . "Extracting Vessel Dimensions from 2D Fluorescence Microscopy Images in MATLAB"^^ . "<pre><code>`code`\n</code></pre>\n<pre><code>clear all\nclose all\ngcp = [715800.552 269485.589 147.297;\n715158.090 269844.880 145.997;\n715696.346 269859.321 150.967;\n715832.619 269722.758 149.977;\n715871.711 270342.277 155.387;\n715274.340 270409.330 151.777;\n715302.550 270693.090 155.417;\n716245.202 270290.139 162.067;\n715444.307 269891.193 148.737;\n715846.318 269927.167 151.687;\n715910.530 270335.100 155.727;\n715578.256 270648.775 156.667];\nomega=0;\nr_omega=[1 0 0;0 cos(omega) -sin(omega);0 sin(omega) cos(omega)];\nfi=0;\nr_fi=[cos(fi) 0 sin(fi);0 1 0;-sin(fi) 0 cos(fi)];\nkappa=pi/2;\nr_kappa=[cos(kappa) -sin(kappa) 0;sin(kappa) cos(kappa) 0;0 0 1];\nR=r_omega*r_fi*r_kappa;\nck=152.34;\nZ0=850;\nX0=715667.056;\nY0=270102.907;\nxi0=0;\neta0=0.000003;\nxi_sz=zeros(12,1);\neta_sz=zeros(12,1);\nA=zeros(24,6);\nfor i = 1:12\n xi_sz(i,1)=((R(1,1)*(gcp(i,1)-X0)+R(2,1)*(gcp(i,2)-Y0) + ...\n R(3,1)*(gcp(i,3)-Z0))/(R(1,3)*(gcp(i,1)-X0)+R(2,3) * ...\n (gcp(i,2)-Y0)+R(3,3)*(gcp(i,3)-Z0)))*(-ck)+xi0;\n eta_sz(i,1)=((R(1,2)*(gcp(i,1)-X0)+R(2,2)*(gcp(i,2)-Y0) + ...\n R(3,2)*(gcp(i,3)-Z0))/(R(1,3)*(gcp(i,1)-X0)+R(2,3) * ...\n (gcp(i,2)-Y0)+R(3,3)*(gcp(i,3)-Z0)))*(-ck)+eta0;\nend\nfor i = 1:12\n A(i,1)=-ck*((-((sin(omega))*(gcp(i,1)-X0)+(-sin(omega) * ...\n cos(fi))*(gcp(i,2)-Y0)+(cos(omega)*cos(fi)) * ...\n (gcp(i,3)-Z0))*(cos(kappa)*cos(omega))) / ...\n ((sin(omega))*(gcp(i,1)-X0)+(-sin(omega)*cos(fi)) * ...\n (gcp(i,2)-Y0)+(cos(omega)*cos(fi))*(gcp(i,3)-Z0))^2) ...\n +ck*((sin(omega)*((cos(kappa)*cos(omega)) * ...\n (gcp(i,1)-X0)+(sin(kappa)*cos(omega)+sin(omega) * ...\n sin(fi)*cos(kappa))*(gcp(i,2)-Y0)))/((sin(omega)) * ...\n (gcp(i,1)-X0)+(-sin(omega)*cos(fi))*(gcp(i,2)-Y0) + ...\n (cos(omega)*cos(fi))*(gcp(i,3)-Z0))^2) + ck * ...\n (((sin(omega))*((sin(kappa)*sin(omega)-sin(omega) * ...\n cos(kappa)*cos(omega))*(gcp(i,3)-Z0))) / ...\n ((sin(omega))*(gcp(i,1)-X0)+(-sin(omega) * ...\n cos(fi))*(gcp(i,2)-Y0)+(cos(omega)*cos(fi)) * ...\n (gcp(i,3)-Z0))^2)\nend\nfor i= 1:12\n N2=(cos(kappa)*cos(omega))*(gcp(i,1)-X0)+(sin(kappa) * ...\n cos(omega)+sin(omega)*sin(fi)*cos(kappa)) * ...\n (gcp(i,2)-Y0)+(sin(kappa)*sin(omega)-sin(omega) * ...\n cos(kappa)*cos(omega))*(gcp(i,3)-Z0);\n D2=(sin(omega))*(gcp(i,1)-X0)+(-sin(omega)*cos(fi)) * ...\n (gcp(i,2)-Y0)+(cos(omega)*cos(fi))*(gcp(i,3)-Z0);\n A(i,2)=-ck*((D2*(-(sin(kappa)*cos(omega)+sin(omega) * ...\n sin(fi)*cos(kappa)))-N2*(sin(omega)*cos(fi)))/(D2^2))\nend\n</code></pre>\n<p>the second for cicle sucessfully fills up my A matrix, but the last for cicle deletes the filled up elements from the 1st column as its fills the 2nd one</p>\n<p>I tried writing the second and last for cicle into 2 different varriables,(vectors) and mixing the A matrix from those, but same problem occurs</p>\n"^^ . "i.e. the naive loop I have above (in the second part of the snippet) -- or do you mean something else? Is that really the fastest way?"^^ . . "TypeInitia​lizationEx​ception, BadImageFormatException using a .net assembly created in MatLab 2019b 64bit"^^ . "0"^^ . . . . . . . . . "<p>Good afternoon. I want to write a code to output experimental frequency response for system identification. For verification I use the modeled sinusoid and the response of the modeled system. To exclude the influence of transient process and in the future measurement noise, I want to determine the amplitude and phase of the system output using Fourier analysis. The amplitude is fine, but the phase is a problem.</p>\n<p>I tried my own code and the code from Matlab doc. I decided on the code from the video: <a href="https://www.youtube.com/watch?v=ZvYGqYOyesk" rel="nofollow noreferrer">https://www.youtube.com/watch?v=ZvYGqYOyesk</a>. I still have a problem with the phase. I watch amplitude and phase at the input frequency respectively. I compared with the results of lsqcurvefit. My code:</p>\n<pre><code>close all, clear, clc;\n\nstep_t = 0.01;\n\nT = 5;\nw = (2*pi)/T;\nAm = 2;\n\nt_real = 0:step_t:100;\n\nsin_mass = Am*sin(w*t_real);\n\nTf = 10;\nsys = tf([0 1],[Tf 1])\n\ny = lsim(sys,sin_mass,t_real);\n\nfigure()\nplot(t_real, sin_mass, t_real, y),grid on\nlegend('input','output')\n\n[f,F_x_f]=fourier(t_real,y,'sinus');\n\n% plot the magnitude spectrum\nfigure(2)\nstem(f,abs(F_x_f))\ngrid on\nxlim([0,20])\nxlabel('Frequency in Hz')\nylabel('Amplitude spectrum of the force in N')\n\n% plot the phase spectrum\nfigure(3)\nstem(f,angle(F_x_f))\ngrid on\nxlim([0,20])\nxlabel('Frequency in Hz')\nylabel('Phase spectrum of the force in °')\n\n[M,I] = min(abs(f-(1/T)));\n\nout_prob = F_x_f(I);\n\nAmplitude_est = abs(out_prob)\nPhase_est = angle(out_prob)\n\nf_out = @(x,u)x(1)*sin(w*u + x(2));\n\npar0 = [Am,0];\n\npar_out = lsqcurvefit(f_out, par0, t_real, y')\n\ny_est = par_out(1)*sin(w*t_real + par_out(2));\n\nfigure()\nplot(t_real, y, t_real, y_est),grid on\nlegend('output','output est')\n</code></pre>\n<p>Function fourier from the video:</p>\n<pre><code>function [f,X_f]=fourier(t,x_t,modus)\n % check if mode is set\n if nargin&lt;3\n % set to default value\n modus='pulse';\n end\n \n % Number of values -&gt; scalar\n N=length(t);\n\n % maximum time (in s) -&gt; scalar\n t_max=t(N);\n % Time step (in s) -&gt; scalar\n t_step=t(2);\n % maximum frequency (in Hz) -&gt; scalar\n f_max=0.5/t_step;\n \n % perform Fourier transform -&gt; vector of length N\n if strcmp(modus,'pulse')\n % the unit of the spectrum is 1/Hz (e.g. V/Hz, A/Hz, ...)\n XX(1:N)=t_max/(N-1)*fft(x_t); \n elseif strcmp(modus,'sinus')\n % the unit of the spectrum is 1 (e.g. V, A, ...)\n XX(1:N)=2/N*fft(x_t);\n else\n error(['The modus ',modus,' is unknown.'])\n end\n % Meaning:\n % for even N:\n % XX(1) contains the DC component (real)\n % XX(2:N/2) contains the positive frequency components in ascending order (usually complex)\n % XX(N/2+1) contains the highest frequency (real)\n % XX(N/2+2:end) contains the negative frequency components in decreasing order (usually complex)\n % for odd N:\n % XX(1) contains the DC component (real)\n % XX(2:(N+1)/2) contains the positive frequency components in ascending order (usually complex)\n % XX((N+3)/2:end) contains the negative frequency components in decreasing order (usually complex) \n \n % check whether N is even or odd\n if mod(N,2)\n % N is odd\n % create frequency spectrum -&gt; row vector\n X_f(1:(N+1)/2)=XX(1:(N+1)/2);\n % create frequency range (in Hz) -&gt; row vector\n f=linspace(0,f_max*(N-1)/N,(N+1)/2);\n else\n % N is even\n % create frequency spectrum -&gt; row vector\n X_f(1:N/2+1)=XX(1:N/2+1);\n % create frequency range (in Hz) -&gt; row vector\n f=linspace(0,f_max,N/2+1);\n end\nend\n</code></pre>\n"^^ . "1"^^ . . . . . . "0"^^ . . "1"^^ . . "machine-learning"^^ . . . "how to get a transparent background in Matlab for wordcloud"^^ . "1"^^ . . . . . . "0"^^ . . . . . "0"^^ . "1"^^ . . . "0"^^ . "4"^^ . "2"^^ . . . . "0"^^ . "<p>I am a student studying MATLAB. I am working on creating a code for convolution without using the conv2 function.</p>\n<p>To perform the convolution, I first need to create a grayscale image, but I am encountering an issue.</p>\n<p>The grayscale image created using the rgb2gray function and the grayscale image created using my custom code have slightly different values. I believe this is due to floating-point issues, where the rounding doesn't work properly, and the values differ. Rounding does not work correctly for values with a decimal of 0.5. Even though I added code to manually round the values, the problem persists.</p>\n<p>How can I make sure that the difference between the two images (the grayresult value) becomes 0? Could you please help me with this?</p>\n<pre><code>enter code here\nclc;\nclear;\nclose all;\n\nimage = imread(&quot;KakaoTalk_20250321_165344568.png&quot;);\n\n\n% --------------grayscale applied using a function-----------------------\n\ngrayfun = rgb2gray(image);\n\n\n% ----------------Grayscale without a function--------------------------\nfor i = 1:size(image,1)\n for j = 1:size(image,2)\n R(i,j) = image(i,j,1);\n G(i,j) = image(i,j,2);\n B(i,j) = image(i,j,3);\n end\nend\n\nR = double(R);\nG = double(G);\nB = double(B);\n\n% gray = R*0.2989 + G*0.5870 + B*0.1140;\n\ngray = R*0.298926034245627 + G*0.587034707055387 + B*0.114039258699985;\n\ngray2 = gray\n\n##-----------------Manually rounding------------------------------------\n\nfor i = 1:size(image,1)\n for j = 1:size(image,2)\n\n decimal_part = gray(i, j) - floor(gray(i, j));\n first_decimal = floor(decimal_part * 10);\n\n if first_decimal &gt;= 5\n\n grayman(i, j) = ceil(gray(i, j));\n else\n\n grayman(i, j) = floor(gray(i, j));\n end\n end\nend\n\n%-----------------------------------------------------------------------\n\ngrayman = uint8(gray);\n\n\n\n%---------------Subtraction calculation-----------------------------------\ngraysubresult = sum(sum(abs(grayfun) - abs(grayman)));\ngrayresult = abs(grayfun) - abs(grayman);\n</code></pre>\n"^^ . . . . . "How to perform OLS regression in Matlab with constraints on coefficients?"^^ . . "For a start, is this Octave code rather than MATLAB code? `endif` is not valid MATLAB syntax, it would be best if you tagged your question for the specific language you're using to get answers you can definitely use."^^ . . . . "random"^^ . . . "0"^^ . "1"^^ . . . . . . . . . . . . "<ol>\n<li>I have tried to do this using a C caller block and then using C++ vectors, but the error that arises suggests C caller blocks do not support C++. Is this correct?</li>\n<li>Next I tried to use a Matlab Function block, with which I attempt to call code in my C file. However, it seems to object to calling a C function of multiple inputs with a coder.ceval statement and I'm just wondering if this is actually possible? If so, what should the syntax be?</li>\n</ol>\n<p>I am doing this for someone else on their pc and do not have it on my pc, so can't see it right now, but as I recall, my effort was something like this:</p>\n<pre><code>function [a,b,c,d] = callingCcode (x,y)\nx = coder.ceval('Ccode',(x,y))\n</code></pre>\n<p>It seems to object to the multiple inputs in the coder.ceval line, as I say. Having just taken a look at coder.ceval, I see it can only return a single scalar output. I want it to return more than one double as an output, so I'm just wondering if it's not possible this way and if so, whether there's any other way to do this? What I'm seeking to do again is to have a block with multiple inputs and outputs which calls C Code.</p>\n"^^ . "<p>It could be done other way around</p>\n<p>You could take IT++ random module and convert it to\nMEX function, callable from MATLAB</p>\n"^^ . "MATLAB transform XML file into pointcloud"^^ . . "0"^^ . . . . "2"^^ . . "<p>Mathworks did not add some basic features as single cell run in visual studio code. You can run all the code or run selection. But there is no way to run current cell. The cells are divided by %%. Is there a way to select all the code between %% to then run selection? Select to bracket can only select the code between default brackets ()[]{}, but not %%. Is there a way to run or just select the cell?</p>\n<p><a href="https://i.sstatic.net/pzYZqtcf.png" rel="nofollow noreferrer">matlab cell</a></p>\n"^^ . "@jdweng where? Thanks!"^^ . . "1"^^ . . . "how to make symmetric padding?"^^ . . . . "0"^^ . . "0"^^ . . . . . . "floating-point"^^ . . "code-generation"^^ . . "<p>In matlab, the function <code>fitcsvm</code> trains a support vector machine.\nIn output, there is a component <code>BoxConstraints</code>. I have read the post <a href="https://stackoverflow.com/questions/31161075/svm-in-matlab-meaning-of-parameter-box-constraint-in-function-fitcsvm">this post</a>\nand understood the meaning of box constraint.</p>\n<p>But in the answer of the post, the box constraint C is a scalar, while in the output of Matlab it is a vector with same length of number of samples, and it is all 1, where I have used default box constraint 1 in the input.</p>\n<p>I do not understand what is the output.</p>\n<p>(I have read the sections of SVM on <em>the Element of Statistical Learning</em>, and did not find this term. So I think perhaps it is different choice of term. If you would like to answer, you could skip explaining basic concepts of SVM.)</p>\n"^^ . . . "-1"^^ . . . . "<p>With the following 2 support functions</p>\n<p>1.-</p>\n<pre><code>function [a b c d]=plane_points_to_coeffs(A,B,C)\n% input : 3 plane points\n% output : [a b c d] plane coefficients\n% no check whether 3 points may be parallel\nx1=A(1);y1=A(2);z1=A(3);\nx2=B(1);y2=B(2);z2=B(3);\nx3=C(1);y3=B(2);z3=C(3);\na=(y2-y1)*(z3-z1)-(z2-z1)*(y3-y1);\nb=(z2-z1)*(x3-x1)-(x2-x1)*(z3-z1);\nc=(x2-x1)*(y3-y1)-(y2-y1)*(x3-x1);\nd=-(a*x1+b*y1+c*z1);\n</code></pre>\n<p>2.-</p>\n<pre><code>function L=dist_point_plane(P,a,b,c,d)\n% input point P = [x y z]\n% input plane coefficients [a b c d]\n% L : output distance point to plane\nL=abs(a*P(1)+b*P(2)+c*P(3)-d)/(a^2+b^2+c^2)^.5;\n</code></pre>\n<p>and script</p>\n<pre><code>% 1st object\nA1 = [-50.0098 -181.0869 -37.5881];\nB1 = [-49.8410 -180.8097 -41.1383];\nC1 = [-49.5887 -180.3952 -46.4462];\n% 2nd object\nA2 = [-50.199 -180.93 -37.249];\nB2 = [-50.256 -180.823 -33.686];\nC2 = [-50.341 -180.657 -28.359];\n% 1st plane\n[a1 b1 c1 d1]=plane_points_to_coeffs(A1,B1,C1);\n% 2nd plane\n[a2 b2 c2 d2]=plane_points_to_coeffs(A2,B2,C2);\n\n% distances 1st plane to points on 2nd object\nL_plane1_A2=dist_point_plane(A2,a1,b1,c1,d1)\nL_plane1_B2=dist_point_plane(B2,a1,b1,c1,d1)\nL_plane1_C2=dist_point_plane(C2,a1,b1,c1,d1)\n\n% distance2 2nd plane to points on 1st object\nL_plane2_A1=dist_point_plane(A1,a2,b2,c2,d2)\nL_plane2_B1=dist_point_plane(B1,a2,b2,c2,d2)\nL_plane2_C1=dist_point_plane(C1,a2,b2,c2,d2)\n</code></pre>\n<p>I obtain</p>\n<pre><code>L_plane1_A2 =\n 1.035855768604593e+02\nL_plane1_B2 =\n 1.034733625214198e+02\nL_plane1_C2 =\n 1.033053734283317e+02\nL_plane2_A1 =\n 1.018878096607852e+02\nL_plane2_B1 =\n 1.017752913940908e+02\nL_plane2_C1 =\n 1.016071380599225e+02\n</code></pre>\n<p>I have corrected the error kindly pointed by Jonathan in <code>plane_points_to_coeff</code></p>\n<p>Now, I got the distance(point,plane) formula from</p>\n<p><a href="https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_plane" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_plane</a></p>\n<p>In this source <code>d</code> has a negative sign.</p>\n<p>I'd like to agree with Jonathan again upon another error here, that <code>-d</code> should be <code>+d</code></p>\n<p>because it makes more sense to calculate with a<em>x+b</em>y+<em>c</em>y+<em>d</em></p>\n<p>but I am going to keep both in this my answer, for the question originator to find out whether</p>\n<p>the formula in Wikipedia is the source of the error, or there's a 30dB distance error and<code> d</code> should remain <code>-d</code> .</p>\n<p>With <code>+d</code> the results agree with Jonathan's</p>\n<pre><code>L_plane1_A2 =\n 0.172913873214268\nL_plane1_B2 =\n 0.060699534174707\nL_plane1_C2 =\n 0.107289558913367\nL_plane2_A1 =\n 0.183549819138508\nL_plane2_B1 =\n 0.296068085832844\nL_plane2_C1 =\n 0.464221420001122\n</code></pre>\n"^^ . . "0"^^ . . "1"^^ . "@jdweng: It is only _PowerShell_ that uses `\\`` as the escape character, and PowerShell is _not_ in the picture when R's `system()` function is called, so your suggestion cannot possibly help. MATLAB's `-r` option does _not_ create a report file, and per [the docs](https://www.mathworks.com/help/matlab/ref/matlabwindows.html) you need either `-r` or `-batch` to execute statements, so your advice is misleading. Please only comment if you understand the question and hand and have subject-matter expertise or you can at least point to documentation to back up your claims."^^ . . "<p>Trying to solve the signal subtraction analytically for <strong>s1-s2=0</strong>,</p>\n<pre><code>exp(-1j*8*pi/lambda*(V^2*ta*time_delay)/R) = 1 ;\n</code></pre>\n<p>Base on the parameters that are fixed, it might be easier for you to solve this equation.</p>\n<p>PS: This is my first answer so forgive me if it is too crude.</p>\n"^^ . "1"^^ . "0"^^ . . . . . . "Octave contour function returns an unaccpected erro message"^^ . "`logical(x)` is another way."^^ . . "-1"^^ . . "1"^^ . . "g++ version 12.2.0 optimizes the outer loop away with flags `-Ofast -mavx2 -mfma`. What compiler flags did you use?"^^ . "0"^^ . "0"^^ . . "0"^^ . . "2"^^ . "A lot is unclear here. Please [edit] the question to clarify. what is IT++ ? Why is this tagged `signal-processing` and `communication` ?"^^ . "Pass parameters to exe-file (compiled from Simulink)"^^ . "0"^^ . . . "2"^^ . . "0"^^ . . . "1"^^ . "0"^^ . . "0"^^ . . . "1"^^ . . . "yes I agree with you magnesium, the Luis and fireflies codes appear to be nearly the same, its very puzzling how different their times are recorded. Perhaps fireflies solution may be avoiding additional overhead with indexing by not defining C as a sparse matrix and then by calculating all of C directly instead of indexing in C. That has its own problems, then Luis' solution would be much more memory friendly."^^ . "discretization"^^ . . . "In addition to removing `ind2db` as Cris said, replacing `x(kk)==0` by `~x(kk)` may help a little"^^ . "0"^^ . . . "Read up on `?system2` and rework your `system` line to use that instead."^^ . . "I have edited the answer. contourf creates filled contours, and contourcmap can modify color"^^ . . . . "0"^^ . "1"^^ . "0"^^ . "`set(gcf,"Position",[200,200,200,200])`, where gcf gets the figure handle, the 4 element vector is (L to R) [X, Y, width, height] on screen. This could be done inside a program or in the command window at any time."^^ . "0"^^ . "Your defining of `R`, `L`, `C`, and `V0` as double values wipes the previously defined symbolic variables of the same names. Just `syms i(t)` is needed in your first line."^^ . . . "Which version of MATLAB are you using? Answers concerning the latest JavaScript-based uifigure interaction might be very different to what came before"^^ . . "<p>I have dowloaded a MATLAB file with species names and their ecological group from <a href="https://ambi.azti.es/download/" rel="nofollow noreferrer">https://ambi.azti.es/download/</a></p>\n<p>In step 5 on this page the file library.mat can be downloaded (zipped). I then use the function readMat() from the R.matlab library to read this file:</p>\n<pre><code>library(R.matlab) \nambi&lt;-readMat(&quot;library.mat&quot;)\n</code></pre>\n<p>I get this 7 warnings:</p>\n<p>Warning messages:</p>\n<blockquote>\n<pre><code>1: In convertUTF8(ary) :\nout-of-range values treated as 0 in coercion to raw \n2: In convertUTF8(ary) :\nout-of-range values treated as 0 in coercion to raw \n3: In convertUTF8(ary) :\nout-of-range values treated as 0 in coercion to raw \n4: In convertUTF8(ary) :\nout-of-range values treated as 0 in coercion to raw \n5: In convertUTF8(ary) :\nout-of-range values treated as 0 in coercion to raw \n6: In convertUTF8(ary) :\nout-of-range values treated as 0 in coercion to raw \n7: In convertUTF8(ary) :\nout-of-range values treated as 0 in coercion to raw\n</code></pre>\n</blockquote>\n<p>I don't know what this means but I suspect it has something to do with encodings. I would be very thankful if someone can tell me what the reason is and how I can solve this problem. I don't have MATLAB. I am using R version 4.4.3 on Swedish Windows 11.</p>\n"^^ . "1"^^ . . . . . "How can I copy & past a curve in yyaxis right to other plot for comparison in Matlab plot?"^^ . . "I found the code ran much faster after I had preallocated the variable `a`. Thanks for your help!"^^ . . "mathematical-optimization"^^ . "STL files are 3D geometry, so that's not exactly "image processing". you need something like Iterative Closest Point (ICP) for alignment of point clouds. I'm sure a variant of that exists for meshes too, or some other algorithm, anyway that's the class of problem you have here. -- if you had *voxel data* instead (as a source), that too can be aligned, without conversion, with other approaches. whatever source data you have is alignable. we just need to know what type of data it is, originally, for best advice."^^ . "0"^^ . . "0"^^ . . "That is correct. For non-scalar outputs you use coder.wref or coder.ref and pass them as inputs to coder.ceval. You need to initialize those variables before passing them to coder.ceval."^^ . . . . . . "<p>I am trying to draw a decision boundary for fisherisis dataset on Matlab. Below is the code that I am working on:</p>\n<pre><code>load fisheriris;\nX = meas(:,1:2);\ny = species;\n\n% PLOT\nfigure;\nplot(X(strcmp(y,&quot;setosa&quot;),1),X(strcmp(y,&quot;setosa&quot;),2),'.','DisplayName','setosa'); hold on\nplot(X(strcmp(y,&quot;versicolor&quot;),1),X(strcmp(y,&quot;versicolor&quot;),2),'.','DisplayName','versicolor');\nplot(X(strcmp(y,&quot;virginica&quot;),1),X(strcmp(y,&quot;virginica&quot;),2),'.','DisplayName','virginica'); hold off\nlegend(&quot;setosa&quot;,&quot;versicolor&quot;,&quot;virginica&quot;)\n\n% SVM\nt = templateSVM(&quot;KernelFunction&quot;,&quot;polynomial&quot;, &quot;BoxConstraint&quot;,1,&quot;KernelScale&quot;,&quot;auto&quot;,&quot;PolynomialOrder&quot;,2,&quot;Standardize&quot;,1);\nSVMModel = fitcecoc(X,y,&quot;Learners&quot;, t);\n\n% DECISION BOUNDARY\n%%% Draw decision boundary here\n</code></pre>\n<p>The above SVMModel I am using is classified multiclass SVM (3 classes: &quot;setosa&quot;, &quot;versicolor&quot;, &quot;virginica&quot;) and 2 first column of the dataset for the train data.\n<a href="https://i.sstatic.net/mLtsVpBD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mLtsVpBD.png" alt="Plot of above code" /></a></p>\n<p>I am expecting that I can plot 2 or 3 lines or curves displaying the boundary of each species in my SVMModel. I have read several websites that somewhat included my problems but nothing works for me because they are using linear SVM or they are using linear equation... Below is list of websites that I have searched about:</p>\n<ol>\n<li><a href="https://www.mathworks.com/help/stats/support-vector-machines-for-binary-classification.html" rel="nofollow noreferrer">First website</a>, but this is for binary classification, in my case, I have 3 classes.</li>\n<li><a href="https://www.mathworks.com/matlabcentral/answers/330665-decision-boundaries-in-svm-multiclass-classification-fisheriris-dataset" rel="nofollow noreferrer">Second website</a>, but this is for linear SVM, in my case is polynomial kernel function.</li>\n<li><a href="https://www.mathworks.com/matlabcentral/answers/412365-how-to-find-the-multi-class-hyperplane-decision-boundaries-using-support-vector-machines-svm" rel="nofollow noreferrer">Third website</a>, but in this situation, the properties of <code>ecoc</code> has the property <code>Beta</code>, in my case the <code>Beta</code> is not provided.</li>\n</ol>\n<p>Anyone have any idea how to draw decision boundary in my situation? Thanks a lot in advance.</p>\n"^^ . . "0"^^ . "try [dsp.se] or [electronics.se]. this doesn't look like an actual programming problem, but a math problem."^^ . . . . "0"^^ . "1"^^ . "Please solve the issue with the grayscale image"^^ . . "visual-studio-code"^^ . . "2"^^ . . . . "0"^^ . . "0"^^ . . "How to freeze certain weights of hidden layer neurons during training in a feedforward network in MATLAB?"^^ .